From among all the qualities that make good code, robustness is one of my favourites. Robustness can be explained as a measure of how hard is to break someone’s code. The opposite of robust code is fragile code; an example of fragile code would be having a class with all its member variables marked as public.
My concern with robustness is that is usually overlooked, is not placed as a priority for some developers, which in my opinion is a mistake. The main problem with fragile code, is that for its correct behaviour, it depends on how the code is being used, and that, in my experience, is synonym of bugs.
The benefits of having robust code are many, some of the most important ones are:
- Easy to change. Robust code is easier to change because external factors don’t affect its behaviour .
- Less bugs. The more robust the code is, the less combinations that cause a bug in the code.
- Better integration. Robust code is predictable, so from an integrator point view, is always going to have the same behavior.
- Consistency. Repeat this with me “Robust code, works fine no matter who, when or how it gets called”.
To help spot fragile code here there is a list of common fragile code patterns.
- Public getters / setters / fields.
- Bad equals / hashCode / compareTo methods.
- Code duplication.
- Use of plain constants when an enum should be used.
- Not providing with any factory or build pattern for complex objects.
- Dependency on global variables.
- Coding against implementations and not interfaces.
One of the things that upsets me from modern frameworks is that they push you to create non robust code, they sometimes force you to have default constructors, getters and setters for all instance variables… but there’s no much we can do about it, and sometimes the advantage of using them is worth the hacking, but, from my point of view, fragile code shouldn’t be accepted in any other scenario.
Test code deserves a special mention. Test code is usually seen as not as important as production code, and this causes lots of developers to write very fragile tests. I am sure that anyone who has work in a large project using automated tests will absolutely agree with me that there is nothing more tedious than changing 10 lines of test code for each line of production code that changes, and that can be prevented with robust test code. So when writing test codes, please keep in mind that you have to care for it just as much as if was production code!!!
Find in this article the 10 characteristics of a robust application/service.
- The pyramid of code quality, the 5 characteristics of good code.
- The pyramid of code quality (Part II), the 3 different types of codes.
- How to write a good test case: 5 tips to write better test cases
- How to write readable code? 5 Tips to improve your code readability.
- The obsession with beautiful code, the refactor syndrome.