An Interest In:
Web News this Week
- April 14, 2024
- April 13, 2024
- April 12, 2024
- April 11, 2024
- April 10, 2024
- April 9, 2024
- April 8, 2024
Clean Code Part 1
Clean code is akin to keeping your home/workspace tidy. Cleaning requires effort, whereas leaving garbage doesnt.
While Id love to mention some examples of poor code Ive 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 youll 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.
Move hard-coded values to the database
Instead of this
do this...
Its very easy to write constants such as tax rates and bool switches directly into your code without thinking about the long term repercussions. Im 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
Guard clauses follow the fail-fast principle. In the example above Im performing a null check on the injected
IEmailService
reference supplied to the constructor (assume Im 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 Ive compacted an IF statement to one line. You dont have to do this, but I find it creates less noise and is more succinct.
Choosing appropriate class names
Poor class names
Class names typically work best when they are nouns. However in more complex scenarios as shown above it is easy to fall foul of this when you need to describe two related classes.Heres one solution to fix this:
This is much cleaner and concise. Ive used inheritance by creating a base class of
Customer
and 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, Im 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.
In part 2 well discuss more hints and tips for keeping your code clean.
Thanks for reading!
Original Link: https://dev.to/dalbirburhm/clean-code-part-1-378n
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To