Making your code more testable

Testability is one of the most beautiful, desireable and must have feature that a code must be compliant. Nowadays there is no space for untested and low quality code, that means many problems at production environments, long hours debugging code, and late delivery.

As usual, this is again a farly big subject that I will try to resume in few tips to improve code’s testability as follow :

First of all, start designing and writing a test for your code before you write your business code, just follow test driven development approach.

Never write long methods, because it will probably lead to low quality code and cluttered design, as a result it will make your test very difficult. If there is a need for such a big calculation, temporary variables or things like this, then just split the big method into smaller methods and delegate your calls.

Add the right responsibility to the right object, another smell that will make your tests hard is when one object knows too much about the other object’s internals.

Try to write cleaner and less code, because less you write, less errors you’ll produce/find, and faster will be your program.

Singletons are usually evil for tests, because they usually cache some data that may hurt you.

Leave a comment