6 Best Practices For Writing Clean Code
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." - Martin Fowler.
In the rush to advance software development and streamline project management, writing high-quality code may not always be considered a priority. But this is counterproductive. It doesn’t matter how beautiful a new app may look, if the underlying code is hard to read then it’s going to be a problem to maintain, update or scale it.
In the real world, it’s almost certain that someone else will eventually need to read and modify your code. If they have to spend hours or days trying to understand it before they can fix a minor problem, then something ain’t right!
It can be overly simplistic to think of code in binary terms of ‘good’ or ‘bad’ - rating code is a value judgment relative to the context in which it is being read and used. Moreover, almost all code can be improved over time, particularly as programming languages evolve and new solutions emerge.
However, there are some general red flags that all developers will know about. A codebase is usually considered ‘bad’ when it is overly complex, hard to understand or maintain, has too many dependencies, or simply doesn’t do what it is supposed to (at least, not in the most efficient way).
Why is it a problem? Well, in 1996 the Ariane 5 space rocket self-destructed seconds after lift-off due to a single software bug that had been inadvertently copied over from the software used for the Ariane 4 launches. This may be an extreme example - the explosion caused an estimated loss of $370m - but problems with complex or inaccessible code can cost countless hours and significant resources at any business.
A 2018 study by Stripe found that the average software developer spends around 17 hours a week on maintenance issues such as debugging, and nearly four hours a week working to clean up ‘bad code’. It calculated that the opportunity cost of this inefficient use of developer time reached around $85bn annually. It doesn’t matter if your team adopts Agile thinking or Extreme Programming techniques if significant resources are lost because things weren’t done right in the first place.
So clean code is important. But what is it, exactly? Defining ‘clean code’ with precision can be tricky as it may vary significantly according to the programming language being used and the problem is solved. But there are some universal clean code principles: arguably the most important is that code is easy to understand and can be worked on by anyone that needs to.
By ‘everyone’ we typically mean the other software developers or engineers on your team. But ideally, your code will also remain easy to understand for other developers that may be involved in the project at some point in the future. This will make maintenance, updates, and troubleshooting much easier down the line. As Robert C Martin (a.k.a “Uncle Bob”) noted in his book ‘Clean Code: A Handbook of Agile Software Craftsmanship’, the only truly valid measurement of code quality is the number of ‘WTFs’ per minute when someone else is reviewing it.
Best practices for writing clean code
No one is saying that writing clean, elegant, and accessible code is easy. The French philosopher Blaise Pascal famously wrote ‘I would have written a shorter letter, but I did not have the time’, neatly capturing the challenges of conveying a message that is both clear and concise. Developers face a similar challenge.
The important thing to remember is that getting it right will have huge and long-lasting repercussions for your organization (and your future workload!). In other words, it’s worth putting in the effort now to save hassle later. Here are six tips to write clean code and become a quality software craftsman:
1. Keep it simple: If the best code is easily read and understood by others, then it’s almost always the case that ‘less is more’. Don’t try to over-complicate things - the goal is to write the least amount of code to solve any given problem. Avoid duplicating code wherever possible so that it is easier to navigate and maintain. It’s also good manners to use reader-friendly formatting for your code to save your future self or others time when working on it.
2. Use meaningful names: Your coding will include all kinds of variables, functions, and classes, so it’s crucial to use appropriate names for them. This should reveal the intent with a clear and descriptive name - a verb or noun - and be easy to pronounce and search for. Avoid using slang or offensive words, and be sure to only use one word per concept. Wherever possible, stick to conventional standards to make your code easier to read.
Don’t be cute/offensive with your naming.
abort() //source: https://dzone.com/articles/naming-conventions-from-uncle-bobs-clean-code-phil
3. Respect the Single Responsibility Principle (SRP): Every class, function, or method should have a clearly defined goal - they should do one thing, and do it well. This will keep functions small and make them more testable, while also making it easy for other developers to add other functions as required. This is a key part of the quality control you should be conducting on your code.
4. Use comments, but sparingly: Comments are a useful way to show others what you are trying to do with a particular piece of code. It’s like good ‘customer service’ - providing support for future users of your code. But too many unnecessary comments may end up being confusing and make the code harder to maintain. Remember, the best code won’t need to be explained. If you find yourself scribbling comments everywhere, it’s probably time to just rewrite the code.
5. Include Unit-Tests: Writing unit tests will improve the quality of code, making it more flexible and easier to maintain. Test-driven development (TDD) is a software process that involves writing tests before completing the code so that you can see what the code needs to achieve and how to keep it simple. The three laws of TDD are:
- You may not write production code until you have written a failing unit test
- You may not write more of a unit test than is sufficient to fail, and not compiling is failing
- You may not write more production code than is sufficient to pass the currently failing test.
Beyond this, remember that whatever the product or service, your test code is just as important as your source code. The Quality Assurance engineers on your team will thank you later.
6. Keeping striving for improvement: The best way to improve the quality of your code is to practice writing it. And to keep learning from more experienced developers. With time you’ll start to find ways to optimize your code even without external help, giving you more personal satisfaction and making you a valuable member of any software development team.
If you want to stay up to date with all the new content we publish on our blog, share your email and hit the subscribe button.