Why we need Clean Code?
Why clean code matters, what makes code clean (meaningful names, small functions, guard clauses, comments that explain why) and how to bring the practice into your team.
Why we need Clean Code?
Every software is written once but it is read many times, by the same developer after few months, by the new team member, by the reviewer and by the support engineer who is fixing an issue at midnight. The code which is hard to read will slow down every one of them. It is directly increasing the time to deliver a new feature and the time to fix a bug, which will have direct impact on our customers. In this article, we are going to see why clean code is important, what makes a code clean and how we can bring this practice into our day to day work.
TL;DR Summary
- Code is read much more than it is written, so readability comes first.
- Unclean code is not a cosmetic problem, it slows down delivery and increases the bugs.
- Clean code is simple, readable, small, well named and tested.
- Meaningful names are the cheapest way to make the code clean.
- Functions should be small and do only one thing.
- Comments should explain “why”, the code itself should explain “what”.
- Leave the code better than you found it (Boy Scout Rule).
Challenges
Code is read more than written
Normally, a developer spends most of the time reading the existing code before writing a new line. When the code is not readable, the developer has to spend more time to understand the intention of the original author, sometimes he has to debug it line by line to know what it is doing. It is a hidden cost, nobody is measuring it, but every team is paying it daily.
Fear of change
When the code is messy, developers are afraid to touch it. Small change in one place is breaking something in another place, and nobody knows why. As a result of this, the team starts adding new code around the old code instead of fixing it, and the mess is growing further. Over the period, the simple change which should take one hour is taking one week.
Slow onboarding
New team members take longer time to become productive when the code is not clean. They need someone to explain each module, which takes the time of senior developers too. It is a ripple effect, one unclean module is slowing down more than one person.
More bugs, longer MTTR
Bugs like to hide in complex code. When the method is 300 lines long with nested if-else conditions, it is very hard to see the edge cases. And also, when there is an issue in production, it takes longer time to find the root cause, hence the Mean Time To Resolve (MTTR) is increasing and the customer is waiting.
What is Clean Code?
Clean code is the code which is easy to read, easy to understand and easy to change by any developer in the team, not only by the person who wrote it.
In simple terms, clean code reads like a well written prose. When you read the method, you understand what it does without jumping to five other classes. Robert C. Martin (Uncle Bob) popularised this term with his book “Clean Code”, and it is a good place to start with for beginners.
Think about a kitchen in a restaurant. A clean kitchen doesn’t mean the chef is cooking slowly, in fact, it is the reason he can cook fast. Every knife is in its place, every ingredient has a label. Messy kitchen is working fine for one day, but on a busy weekend it will become a disaster. Code is the same.
Why Clean Code is important?
In order to reduce the time to understand the code, to reduce the fear of change and to reduce the bugs and MTTR, we should write clean code from the first day. It is not an extra effort which we can do later, because “later” never comes in most of the projects.
Clean code helps us to,
- deliver the features faster, since the developers understand the code quickly.
- reduce the bugs, since the logic is simple and visible.
- write unit tests easily, since the classes and methods are small.
- onboard new members faster.
- keep the technical debt under control.
Characteristics of Clean Code
Let us take a closer look at the key characteristics with examples. We will use a simple fund management domain as the running example.
Meaningful names
Names are everywhere in the code: variables, methods, classes, namespaces. Good name tells the reader why it exists, what it does and how it is used.
Example:
// Bad
public decimal Calc(List<decimal> l, int d)
{
decimal t = 0;
foreach (var x in l) t += x;
return t / d;
}
// Good
public decimal CalculateAverageUnitPrice(List<decimal> dailyUnitPrices, int numberOfDays)
{
decimal totalUnitPrice = 0;
foreach (var unitPrice in dailyUnitPrices) totalUnitPrice += unitPrice;
return totalUnitPrice / numberOfDays;
}
The second method is longer by few characters, but nobody needs to ask what it is doing.
Small functions that do one thing
A function should do one thing, it should do it well and it should do it only. When you find “and” in the description of a method (validates the fund and saves it and sends the email), it is a sign that the method needs to be split.
public void PublishFund(Fund fund)
{
ValidateFund(fund);
_fundRepository.Save(fund);
_notificationService.NotifySubscribers(fund);
}
Now each step is one method and the top level method reads like a story.
Avoid deep nesting
Deep nested if-else is very hard to follow. Use guard clauses to return early.
// Bad
if (fund != null)
{
if (fund.IsActive)
{
if (fund.Units > 0)
{
// actual logic
}
}
}
// Good
if (fund == null || !fund.IsActive || fund.Units <= 0)
return;
// actual logic
Comments explain why, not what
When the code needs a comment to explain what it is doing, then most of the time, the code is not clear enough. Rename the variable or extract a method instead. Use the comments to explain “why” a decision was taken, i.e. business rule, workaround for a third-party bug, etc.
// Bad
// check if fund is closed
if (fund.Status == 3) { ... }
// Good
if (fund.IsClosed) { ... }
// Good comment - explains why
// Regulator requires the unit price to be rounded to 4 decimals.
var unitPrice = Math.Round(rawPrice, 4);
Consistent formatting
Agree the formatting rules within the team and follow them in all projects. Use the Visual Studio formatting settings and tools like StyleCop to keep it consistent, otherwise every file will look like written by a different team.
Don’t repeat yourself (DRY)
Same logic copied in multiple places is a bug waiting to happen. When the rule is changed, someone will update only one place. Extract the duplicated code into a method or a class.
How to bring Clean Code into the team?
Here are some practical steps which we can follow,
- Boy Scout Rule - Leave the code better than you found it. When you touch a method, rename one bad variable or extract one small method. Small improvements on every commit add up over the period.
- Code review - Make readability one of the key checks in code review. We will discuss the code review checklist for .NET teams in an upcoming article.
- Coding guidelines - Write down the naming and formatting conventions and keep them in one place.
- Unit tests - Clean code and unit tests support each other. Without tests, nobody will refactor, because of the fear of breaking something.
- Start small - Don’t try to clean the whole code base in one go. Start with the modules which are changing frequently, since they give the most benefit.
Note: Clean code doesn’t mean clever code. One-line LINQ query with five nested lambdas may look smart, but if your team needs ten minutes to understand it, then it is not clean. Prefer simple over clever.
Wrap up
In this article, we have looked at the challenges of unclean code, what is clean code and the key characteristics like meaningful names, small functions, guard clauses and comments that explain why. I really appreciate that you took the time to read this article and I hope this article provided you some insights into clean code. In the next article, I will walk you through the SOLID principles, starting with Single Responsibility and Open/Closed principles.
Related Posts
What is a God object and how to break it?
God objects explained through their warning signs, causes, and a step-by-step refactoring approach using characterization tests, extraction, interfaces, and dependency injection.
Code review checklist for .NET teams
A practical .NET code review checklist covering design, readability, correctness, errors, security, performance, testing, operations, and constructive review comments and discussion.
How to do TDD (Test-Driven Development)?
Test-Driven Development explained through the Red-Green-Refactor cycle and a step-by-step fund-universe example built with tests first for practical development and design.