Give your variables better values

Sometimes I notice that some developers are quite good at giving good names to variables but they are not paying much attention to actual variable values. Usually, it happens in test cases. I absolutely got the reason why it happens: tests are written after the implementation, people are in rush and destructed by annoying static analysis issues, you name it.

Code is written for people and only then for machines. So when it comes to reading through the tests cases written in such manner we become confused. Take a look at this example (in pseudo-code):

def processPaymentIfRegionIsValid
    String region = "region1";
    when(regionValidator).isValid("region1").itReturns(true);
    
    paymentProcessor.withRegionValidator(regionValidator).run(user);
    
    verify(paymentProcessor.processed).isTrue;
end

From implementation point of view test is valid and it does its job, but region1 it's a real problem here:

  1. Poor readability. Ultimately region1 value holds the same (none) meaning as var1 for variable names.

  2. It's a fake value because it doesn't belong to the domain. It means that newcomers or people who are fresh to this domain will falsely assume that region1 is a possible value.

  3. It hides an example of real values. Usually, documentation is quiet in general and finding a list of possible regions could be a problem, which may require asking around people who have this knowledge. It will be better to use here instead of region1 real value like APAC or even have separate test cases for every possible (supported) region value.

To tackle all of mentioned issues is quite easy, just give it a good value:

def processPaymentIfRegionIsValid
    String region = "APAC";
    when(regionValidator).isValid("APAC").itReturns(true);
    
    paymentProcessor.withRegionValidator(regionValidator).run(user);
    
    verify(paymentProcessor.processed).isTrue;
end

Get the latest posts delivered right to your inbox.