Clean code is akin to keeping your home/workspace tidy. Cleaning requires effort, whereas leaving garbage doesn’t.
While I’d love to mention some examples of poor code I’ve seen over the years, I too have fallen foul in the past.
Clean code isn't about vanity! Large messy un-refactored code only adds to technical debt. When another developer works with the same code you’ll have to double the time for them to complete the task due to messy code. Bear in mind time and effort can quickly grow exponentially as each developer hacks and contributes to the same messy code.
Below are suggestions to help keep our code clean.
Instead of this…
It’s very easy to write constants such as tax rates and bool switches directly into your code without thinking about the long term repercussions. I’m referring to changing values.
In cases like these it is far better to move these values into a database table, or at the very least the application configuration file. This way it will be much quicker and safer to make changes as opposed to opening up the code many years later and making changes, compiling and then praying its works while you upload… you get the idea.
Guard clauses follow the fail-fast principle. In the example above I’m performing a null check on the injected
IEmailServicereference supplied to the constructor (assume I’m using DI). If the reference is null, a related exception will be thrown during runtime.
Dealing with null references is an act of life for any developer. Using guard clauses throughout your code promotes error checking and is a good habit to develop.
Eagle eyed developers may have noticed I’ve compacted an IF statement to one line. You don’t have to do this, but I find it creates less noise and is more succinct.
Here’s one solution to fix this:
This is much cleaner and concise. I’ve used inheritance by creating a base class of
Customerand then deriving two subclasses from it. In this instance, it allows for shorter class names since there is some context through the inheritance.
As a final note, I’m not a fan of using inheritance-based models everywhere throughout a solution unless there is a valid case as illustrated above. It can add to unnecessary complexity.
Thanks for reading! 🙂
Part 2 is available here: