What’s wrong with this? Following is an example snippet of code written in C#. It is syntactically correct. It is functionally correct. It accurately returns the results specified by the requirements (that I just made up). Still, there is a major flaw in this snippet of code. This is not a trick question. Can you see the problem?
For (int I = 0; i<100; i++)
{
if(I % 4 == 0) Console.WriteLine(“{0} – mod 4”, i);
else if(I % 2 == 0) Console.WriteLine(“{0} – mod 2”, i);
else Console.WriteLine(“{0} – mod 10”, i);
}
The problem with this code is that it cannot be readily tested. It combines looping with logic. It’s ok to call logic within a loop. It is not ok to embed logic within a loop. If they are combined, the logic cannot be tested outside the context of the loop. This loop is small, so testing wouldn’t be that bad. Even if you were testing manually, you could do a good job.
However, with loops containing many more records, or more complicated logic, this implementation is too complicated. You tests want to be much more granular. As you can see here the rules are:
1) If the number evaluates to mod 4 then print mod 4.
2) If it is not mod 4, but is mod 3, then print mod 2.
3) Otherwise, print mod 10.
You could easily place all of these simple rules into a single method. Once complete you would only need to test a few values in order to consider you function accurate. I would test the integers:
0,1,2,3,4,6,8,9
Test zero because it is neither positive or negative
Test 1, 3, and 9 because they are prime numbers encompassing the first 4 even numbers we test.
Test 2 and 6 to confirm they return Mod 2
Test 4 and 8 to confirm they return Mod 4 and not Mod 2
Testing those few integers provides you with 100% confidence that your method meets your requirements. Anything beyond that is simply testing the compiler.
I know that every person who interviews can come up with questions unique to their experience. I don't find this to be one of those cases. It is a process that is taught in mature software principles. A method should have a signle responsibility. The smaller that responsibility is, the easier it is to confurm accuracy.
Do you disagree with my assessment? Would you test something different? Share your comment below.
Cheers,
Ben