Clean Code: Four Simple Design Rules – Obligatory Read
Join the DZone community and get the full member experience.Join For Free
updated 2/18 : i've clarified the rule #4 and added some links.
i consider the clean code book to be obligatory for every programmer. and if you currently haven’t the time to read it all at once then you should read – and take deep into your heart at least the 12th chapter emergence by jeff langr, which introduces kent beck’s four simple design rules and explains thoroughly what they mean and why they’re so important. the rules, in the order of importance , are:
- runs all the tests
- contains no duplications
- expresses the intent of the programmers
- minimizes the number of classes and methods (this isn't as controversial as it may sound, see below)
stated like this in simple sentences it’s difficult to see the depth hidden behind them and thus their essential importance for clean, high-quality code with high-quality design and i’ll therefore try to explain what they really mean in the full extent based on clean codes. i’ll cite some parts of the book – for i can’t find better words than the author – hoping for the author(s) and publisher graciously permitting it.
runs all the tests – why is it so important to have comprehensive tests 1 , which are run and pass all the time, as this rule implies? foremost because to be actually able to write unit tests, the code must follow the well-known high-quality design principles such as simplicity, single responsibility (including dependency injection), low cohesion etc. – only small, on each other and on the environment maximally independent objects are easy to test.
remarkably, following a simple and obvious rule that says we need to have tests and run them continuously impacts our system’s adherence to the primary oo goals of low coupling and high cohesion. writing tests leads to better designs.
this is no theoretical statement – i’ve personally experienced it many times. see e.g. in test driven development, how do unit tests help drive good design? (answer: they don’t – but they make bad design so painful that you will want to change it).
contains no duplications – “duplication … represents additional work, additional risk, and additional unnecessary complexity.” it can have many forms – lines of code that are same (or similar – adepts for generalization), duplication of implementation (e.g. if a collection has int size() and bool isempty(), isempty shall be based on size() == 0 to reuse the implementation) and other ones. you usually apply abstractions such as template method to remove duplication. the true value is in how it leads to the reduction of complexity.
as we extract commonality at this very tiny level, we start to recognize violations of srp . so we might move a newly extracted method to another class. that elevates its visibility. someone else [...] may further abstract the new method and reuse it in a different context. this “reuse in the small” can cause system complexity to shrink dramatically .
understanding how to achieve reuse in the small is essential to achieving reuse in the large . [ emphasis by jh.]
expresses the intent of the programmers – writing code that expresses well the intent of the programmer so that another person can easily understand it is important for many reasons, especially taking into account that “the majority of the cost of a software project is in long-term maintenance”. expressiveness is also one of the essential requirements of a clean code.
the clearer the author can make the code, the less time others will have to spend understanding it. this will reduce defects and shrink the cost of maintenance .
you can express yourself by choosing good names . we want to be able to hear a class or function name and not be surprised when we discover its responsibilities.
you can also express yourself by keeping your functions and classes small . small classes and functions are usually easy to name, easy to write, and easy to understand.
you can also express yourself by using standard nomenclature. design patterns, for example, … .
well-written unit tests are also expressive. a primary goal of tests is to act as documentation by example . someone reading our tests should be able to get a quick understanding of what a class is all about.
but the most important way to be expressive is to try . all too often we get our code working and then move on … without giving sufficient thought to making that code easy for the next person to read. [ emphasis by jh.]
i’d like to add here that the xp motto “ the code is the documentation ” doesn’t mean, as some people read it, that you simply don’t bother with any comments at all. this is not an elimination of some work, it’s actually a challenging commitment to writing code so, that it reads as documentation – which essentially means that it is maximally expressive. and writing such code is much, much more difficult than typing whatever comes on your mind and then adding few comments here and there. regarding comments and their replacement by expressive method names, the clean code book has a whole, highly inspiration chapter on that. (i have to mention a nice post on why code isn’t documentation , which i’ve quite enjoyed.)
minimizes the number of classes and methods – the least important yet absolutely not negligible rule:
even concepts as fundamental as elimination of duplication, code expressiveness, and the srp can be taken too far. in an effort to make our classes and methods small, we might create to many tiny classes and methods. so this rule suggests that we also keep our function and class counts low.
high class and method counts are sometimes the result of pointless dogmatism. …
i like the mention of “pointless dogmatism”. as too often in religion, pointless dogmatism is a sign of an insufficient, shallow understanding of a principle, its true purpose and the proper context of application. it requires experience, open mind, and reason to apply principles correctly. (by no means want i claim that i have that experience and bright reason .)
please realize that this rule doesn’t suggest you should have only few classes and methods – the 4 rules are ordered by priority and the last one only applies if the previous ones are satisfied . as you certainly noticed, e.g. rule #3 requires “keeping your functions and classes small” and thus also their counts high. but it’s also possible to have too many classes and methods and rule #4 is here to remind you of that and to help you find the right balance. small stuff is easier to understand – but if there is too many (though perfectly understandable) pieces, you won’t be able to see the whole picture. to be concrete: i’ve seen code base where every method was in a class of its own. wouldn’t you agree it’s too many?
the fourth rule is sometimes alternatively stated as "has no superfluous parts", meaning that you should remove all classes and methods that you don't really need to get rid of unnecessary complexity and maintenance overhead. i'd suggest reading the discussion about what "minimize the number of methods/classes" really means . but i feel that this new phrasing isn't an alternative but rather an addition to or a clarification of the original one for you should be really aware when optimally many classes/methods become too many.
- “comprehensive tests” of course doesn’t necessarily mean 100% coverage, which is at least sometimes both impossible and useless (think simple getters/setters, gui). you have to find the right coverage for yourself (though there are arguments that 100% coverage is the ideal goal ).
studying, understanding, and finally applying the rules described above makes it possible to create much better (micro)designs and code and thus quality. as it is the case with zen (as i’ve been told), the basic truths are very simple, but to understand them and to truly master them it takes years and a lot of effort. the important thing is, as the author himself mentions, to try. (i’m myself only somewhere at the beginning of the path. you’ll know i’m there once you see me levitating above my notebook.)
i recommend the clean code book and especially chapter 12 to every programmer but i’m actually not really sure when it’s the right time for a junior programmer to read it for i can imagine that for somebody without sound practical experience both with a beautiful, clean code and with a terrible, low-quality one, the guidelines in the book are way too abstract (however concrete they’re) and difficult to grasp and appreciate – and their appreciation is perhaps the important factor for being motivated and able to put them into practice. but it certainly won’t harm to read it as early as possible and come back to it now and then to discover new depths and resonance with one’s recent experience.
experience and craftmanship is also necessary to be able to apply the clean code principles and guidelines correctly and effectively because, to some extent, one rule always conflicts with another one and you must have some sensibility to the code to be able to find the proper balance between them and to avoid any trace of “pointless dogmatism”.
finally, i’d like to thank all those who help(ed) me understand that – and why – my code is bad and thus lead me towards better quality. please keep on! i’d like to also thank rober pirsig for pointing out the importance of quality to me
- jeff langr’s own summary of the 4 rules
- current xp simplicity rules and older wording of xp simplicity rules (still useful to read, i think)
Opinions expressed by DZone contributors are their own.