Clean Code

Clean Code

Clean code is the name of a book (and there are several other good books on the subject), but for practical purposes, it’s a set of micro practices applied when writing code. A quick summary of clean code practices follows:

Names should be descriptive, unambiguous, specific, correctly spelled, not cute, proportional to the scope, and should not introduce mental mapping.

Methods/functions should be short, do one thing, avoid side effects, take few parameters of which none are booleans, and operate on one level of abstraction.

Comments should be used to describe the why not how, avoid confusing the reader, and not describe the obvious.

Developer testing and clean code practices have quite a lot of common ground! Well-named functions are easier to write unit tests for, because it’s more apparent what to test. Similarly, naming conventions are very important when writing unit tests, which is why at least three big test naming conventions exist. The design of functions/methods has an even greater impact on developer testing. Short functions are directly related to the smallness property of testability, i.e., small things are easier to test. Having functions do one thing also simplifies testing. It’s easier to come up with all necessary test cases, because the functionality is limited. The same goes with functions having short argument lists. The more arguments, the more complex the boundary value analysis becomes. Also, keep in mind that arguments pretty much introduce combinatorial complexity in terms of test cases needed, so having the methods take few arguments is definitely a good thing.

Side effects are directly related to the concepts of indirect input and output, and mandate employment of test doubles. In non-trivial systems, this can’t be avoided, but it’s best that it be done intentionally. In essence, applying clean code practices, especially to method/function design simplifies developer testing to a great extent.