What is a static reference?


A static reference is reference that exists only once for an entire class.  No matter how many instances of that class exist there is only one that one reference.

Why are static references bad?  Because they make testing harder.

Imagine the following class that has a static method:

class Foo{

static int addTax(Item item){
return item.price *=1.65
}

}

You might think that’s easy to test, and you’d be right.  The gnarly part about static references isn’t their logic.  It’s where they are used as they can’t be easily replaced.  Let’s expand on the Foo example.

class Foo{

static int addTax(Item item){
return item.price *=1.65
}

int calculateAll(int items[]){
val total = 0

items.forEach{ item ->
total +=addTax(item);

}

if(total > 100){
total -= 20
}
return total

}

}

It’s bad because the code is equivalent to this:

class Foo{

int calculateAll(int items[]){
val total = 0

items.forEach{ item ->
total += (item.price *=1.65)

}

if(total > 100){
total -= 20
}
return total

}

}

The logic is effectively glued in place.  It reduces the ways in which you can effectively modify variables for testing.  The tax is essentially hard coded.  Since the tax is glued into place it’s not possible to modify the total by adjusting the addTax method.  To be fair it is easy to test this code.

 

However, there’s no denying that this code adds a lot of different options for testing:

interface TaxHandler{

int calculateTax(Item item){

}

}

class Foo(TaxHandler taxHandler ){

 

int calculateAll(int items[]){
val total = 0

items.forEach{ item ->
total += calculateTax(item)

}

if(total > 100){
total -= 20
}
return total

}

}

We can pass in arbitrary TaxHandler implementations to adjust the logic to verify the calculations are correct.

Leave a Reply

Your email address will not be published. Required fields are marked *