5 Steps to Cleaner Code

Chris Smith
5 min readDec 9, 2020
Photo by Oliver Hale on Unsplash

Introduction
There are many benefits to writing clean code, mainly that it makes your code easier to read and understand not just for yourself but also for other developers when they pick it up.

The 5 steps I’ve listed below are nothing new or difficult to understand, what they do is provide a nice introduction into how to start cleaning up your code.

1: Avoid Magic Numbers
Magic numbers refer to hardcoded numbers in code as opposed to using a named constant or enumerated type. The main advantage for removing magic numbers is to increase readability and allow your code to be more self documenting.

In the example below, the first block of code using the magic number 3.99 but what does this value represent? There is a good chance only the original developer knows what this value is, and through time they may even forget.

private decimal GetTotalCost(decimal subtotal)
{
return Decimal.Add(subTotal, 3.99m);
}

Now, lets clean the code by simply adding a constant to replace the magic number. We can see from the code below that the value 3.99 is the cost of postage. This one line addition instantly makes the code more readable and easier to understand.

private decimal GetTotalCost(decimal subTotal)
{
decimal postageCost = 3.99m;
return Decimal.Add(subTotal, postageCost);
}

2: Use Meaningful Names
As with the replacement of magic number, the use of meaningful names is to ensure the code is easy to understand both for the person writing it and others picking it up further down the line. This applies to variables, method names, class names and any other items that require naming within your project.

Take the two lines below, both perform the same function, however the second example is much more descriptive and reduces the need for a comment.

decimal x = 3.99m; // postage cost
decimal postageCost = 3.99m;

Here is another example, this time where the method name isn’t describing the task the method is performing. What does the name TotalCost mean? Is it retrieving, updating or doing some other task with total cost? To understand this you would need to read the code within the method. A better name would be GetTotalCost as this indicates exactly what the method is doing.

private decimal TotalCost(decimal subTotal)
{
decimal postageCost = 3.99m;
return Decimal.Add(subTotal, postageCost);
}

3: Return Early
Returning early from methods is a way of exiting when certain conditions have been met as early as possible. It helps cut down on nested conditions blocks and else statements which in turn improve the code quality/readability.

Using the GetTotalCost method, we may want to return a total cost only when the subTotal parameter is greater than 0. This first example below provides one way of performing this task, however there is a lot of code for what is required and we only return at the end of the method.

private decimal GetTotalCost(decimal subTotal)
{
decimal totalCost;
decimal postageCost = 3.99m;
if (subTotal > 0)
{
totalCost = Decimal.Add(subTotal, postageCost);
}
else
{
totalCost = 0;
}

return totalCost;
}

We can refactor this the above method to return early if the condition is met or carry on if it isn’t. As you can see we have cut down on lines of code and at the same time made the method much more readable and easier to follow.

private decimal GetTotalCost(decimal subTotal)
{
decimal postageCost = 3.99m;
if (subTotal > 0)
return Decimal.Add(subTotal, postageCost);

return 0;
}

This is a very simple example but I’m sure you can see the benefit especially if the code contains a greater level of nesting and if/else statements.

4: Remove Dead Code
While removing dead or unused code won’t change the way your code performs, it will help with code quality and readability by removing noise that isn’t required. When I use the term dead code, I’m referring to any block of code that is no longer called, this can be a class, method, variable etc.

In the example below, the taxRate variable has been added but is never used. Does this mean it shouldn’t be used or there is a missing calculation somewhere? Well, for this example it will never be used, it’s dead code so should be deleted.

private decimal GetTotalCost(decimal subTotal)
{
decimal taxRate = 0.2m;
decimal postageCost = 3.99m;
if (subTotal > 0)
return Decimal.Add(subTotal, postageCost);

return 0;
}

Another candidate for dead code are those lines that invariably get commented out and left in the code base. This not only bloats the code but also leads to confusion as to why they are commented out.

This following is a good example of dead code which should be removed. If the code isn’t required now then do not write it, if it’s already been written then delete it to remove any confusion as to why it’s there. Remember that it will always remain in your repository history should you need it again.

private decimal GetTotalCost(decimal subTotal)
{
//decimal taxRate = 0.2m;
decimal postageCost = 3.99m;
// Leave here as we may want to add tax in the future
//if (subTotal > 0)
//{
// var subTotalIncTax = subTotal + (subTotal * taxRate);
// return Decimal.Add(subTotalIncTax, postageCost);
//}
if (subTotal > 0)
return Decimal.Add(subTotal, postageCost);
return 0;
}

5: Don’t Repeat Yourself (DRY)
The DRY principle is simple in that is means a piece of code should only be written once within an application. Any code that is duplicated should be refactored into a single area, be it a class or method.

Removing duplicated code cuts down on time to read, maintain and test code.

When applying the DRY principle, looking for patterns or similar code as this often points to areas of duplication. Take the example below, there isn’t much to this at the moment but we can already see that the line of code writing the message to the console is duplicated. If we wanted to replace writing to the console with writing to a file, we would need to update both methods.

private void DisplayWelcomeMessage(string userName)
{
var message= $"Welcome {userName}";
Console.WriteLine(message);
}
private void DisplayGoodbyeMessage(string userName)
{
var message = $"Goodbye {userName}";
Console.WriteLine(message);
}

A simple refactor to this above would be of benefit and any changes required to write the message to file would only result in a single method being updated.

private void DisplayWelcomeMessage(string userName)
{
var message= $"Welcome {userName}";
WriteMessage(message);
}
private void DisplayGoodbyeMessage(string userName)
{
var message = $"Goodbye {userName}";
WriteMessage(message);
}
private void WriteMessage(string message)
{
Console.WriteLine(message);
}

Conclusion
The 5 steps above are not difficult to implement and may not have the biggest of impacts. However, putting these in place will be a benefit to both yourself and others.

--

--

Chris Smith

Software Engineer at Kainos. Normally found on a golf course or watching football. All views expressed here are my own.