What is Clean Code?
A: Clean Code is the concept given when the code is well written, so that you read the code and understand exactly what is being done, what is happening, and that each function has its own responsibility.
What is the importance of the Clean Code?
It is known that most of the cost is the maintenance of the project. A code well written and easy maintenance this because it does not take weeks to understand what is being done.
A friend once told me: “I thought when I went to see a code of an expert programmer I wouldn’t understand anything, and it’s exactly the opposite.”
- Clean code is easy to read and understand.
How to write a Clean Code?
- I would say that the crucial start of clean code begins with names. Variable names, method names, class names, and so on.
- Another crucial part is the concept of single responsibility. The function should do one thing and only that. The correct nomenclature may even help in such cases, if you create a function: readFileAndCallWebService, is a sign that the function has more than one responsibility. Honestly, it’s hard to write clean code from the start. It is very easy to write dirty code, spaghetti code and functions with many responsibilities. To avoid these things, it is highly recommended to use the TDD. Since there are automated tests that ensure that the system should do, refactoring is much more effective and reliable.
- I especially like to READ the code, then, a method like this:
It could be written like this:
For so I know what the main method (processFile) does and how it does, without having to open the implementation of each method within it (getFileInformation and callWebService), and methods within it have a single responsibility.
- There are many books of Clean Code, the most famous being: Clean Code – A Handbook of Agile Software Craftsmanship from Robert Martin. I recommend.
- Practice. See how you can improve the code, how can extract, which part to extract.
- Be aware that comments in the code are 99% a bad practice. Clean code is self-explanatory, so put comment would be unnecessary.