In this two-part series, I will show why it is important to write code that is
- easy to read and understand
- easy to change
- easy to test
These are some of the attributes of what is commonly known as Clean Code. I will do this by writing code for a simple use case and then having a short discussion about the code written.
In the first part of this series, I will write the code like an inexperienced developer might write it and then explain why the code is not ideal. In the second part of this series, I will use the Factory Pattern to rewrite the code and explain why that code is much better. Using a Design Pattern is one of the many tools a developer has on his tool belt to write Clean Code.
Our use case
Our application supports a few countries that can be selected one at a time. For each country, we must be able to display some legal documents such as the Terms and Conditions, Disclaimer and Declaration when navigating to the relevant menu items and also in some other sections of the application.
The bad code
An inexperienced developer might write code to retrieve the Declaration, Disclaimer and Terms and Conditions for the selected country as follows:
Is the code easy to understand and read? Well, it’s not too bad. It is straightforward if statements that anyone can read, even non-developers. Keep in mind that in order to read something you must first find it. Because the above functions are strewed all over your codebase it might be slightly difficult to find and thus read. Also, how would you know that you have read everything related to the legalese code?
Is the code easy to change? Although it is relatively easy to update if statements like these, what makes this difficult to change is the fact that you can easily make a mistake. Say you are adding another country, you must make sure you go and add it to all these functions and there is nothing helping you or guiding you or checking that all of them were updated. Even more so if these functions are repeated elsewhere in your codebase.
Changes should also have the minimum impact on your codebase. In this case, where the logic of retrieving the correct legal document is scattered all over the codebase it violates this best practice when an update is made.
Is the code easy to test? This time the answer is no. These functions are part of much bigger classes that probably have a lot of other dependencies. It is not impossible to test this, but it’s going to be very difficult. You can always manually test this after the work has been done, but this is not ideal for regression testing after code changes. So unless you have automated UI testing that stays up to date as the program changes, then this code is not easily testable.
Luckily this is not how we write code at Polymorph.
In the second part of this series I will show you the preferred way to write code for this use case and also explain why it is better.