The clean and quality code matters
The work efficiency formula
Introduction
While I wrote this article from the comfort of my chair and the Covid-19 threatens people’s lives, it did not derail technology development. Software engineers apply engineering principles to software development and problem-solving systems. Their responsibility has increased as products become smarter with microprocessors, sensors and software. More products are based on software to diversify the market, but their software development needs to be coordinated with its mechanical and electrical development work.
This reaches a critical point where the quality of the code matters. Code is a language in which developers express how they can solve a problem. No one brain in the world is similar to another, yet we expect other programmers to read our minds and thoughts. Bad code or Spaghetti code occurs when developers don’t mind the maintenance and the healthy evolvement of the application, which leads to a code that only solves the problem.
The Spaghetti code
Spaghetti code[1] is a derogatory terminology caused by factors such as lack of programming, the inability of the code to comply with a set of programming rules resulting in seemingly minor errors of the code leading to overtime for many people.
This usually leads to somewhat unplanned, complex coding structures that favour GOTO statements over programming structures, resulting in a program that can not be maintained in the long run. For this reason, spaghetti code is considered a nuisance for developers and managers, and it should be avoided.
The term “spaghetti code” came to my acknowledgement from a senior developer who taught me that code quality matters in 2013. But the reference point is from the late 1970s white paper “A Spiral Model of Software Development and Enhancement”[2], which describes the modelling of the code that led to the development of waterfall programming. However, the vast majority of books of that time refer to it as a messy nest of code that lacks the structure required for effective scaling.
The clean code
One of the most outstanding books on the art of clean code is “Clean Code: A Handbook of Agile Software Craftsmanship” by Robert C. Martin [3], which is my primary resource and inspiration to write an article about it. Mr Martin gives a measurement of how to measure the code quality. We calculate a car’s speed by km per hour (at least in Greece). He estimates the code quality by WTFs per minute.
And it is quite true. In my professional career, there are two possible scenarios. In the first scenario, you read a line-by-line code with some wtf reactions, but eventually, you follow the thought process of the other developer and end up with a response like “AAAaaa .. that’s what code does”. In the second scenario, which by the way, is the bad one, you can not process the thinking behind the code to a minimum. The names of the variables do not describe their purpose, and the code, which spans a thousand lines, is not accompanied by any comments or the code isn’t structured into smaller methods or classes. This is the moment that you know that the WTFs per minute go as fast as the speed of light.
It is now evident that there are requirements that make a programmer better than one who is not. But in my experience, it all depends on the willingness to learn. Writing code is simple. It takes time and knowledge. We are not all exposed to coding principles that make our code readable and maintainable. Evolution, however, is the process that we must all go through in our development career to be relevant. In the beginning, you write down some code that feels well-structured. Then, at the coding review, people who are more experienced or talented than us, correcting our mistakes to show us the right direction. It’s indeed simple but not easy.
Learning to write clean code is hard work that requires emotional acceptance of our mistakes. As noted above, coding is somehow our thoughts, and being corrected for something that we genuinely believe is good, is heartbreaking. None of us likes to fail, but it is an initial step to being a good programmer.
How to write good code
Suppose you are familiar with the fact that your code may be bad. Then, you should raise the question of “How to be rich in a week”. Then laugh a little bit because it was a hidden joke in my article that you can review as a bad joke (see that you do not have to be harsh on yourself). So, “How do I write a clean code??”.
Bad news first, there is no easy way to do it. Because if it were easy, everyone would do it. But if you are willing to make this extra mile, you will stand out from several developers. The key is to acquire the “code-sense”, as Mr Martin called it. It’s like cleaning your house, some people have this sense of cleanliness in their DNA, but some have learned it in their lifetime. Messy people can recognize that their homes are dirty but can not clean them. However, grasping the mess and cleaning it separates you from those people.
Pick names that serve their purpose.
The name of the variables, methods, classes and files must be clear and concise. In addition, they need to be written in a language that everyone can understand, such as English. A general coding practice is to write code with variable names in English, as this is the most likely common language among developers. For example, a variable that describes the number one book can be done as follows:
s = “131301301” -----> Bad variable name
sid = “131301301” ------> good variable name
It must not contain special characters. Many programming languages, such as Python, do not support special characters through various encoding options that can be given in a program. With that being said, it is best to avoid variables with special characters as they lead to errors and do not add value to the variable. Therefore, you must adhere to the standard printable ASCII character set to be safe.
s!d = “131301301” -----> Bad variable name
sid = “131301301” ------> good variable name
The last piece of information is the formatting of the variable name. There are many possibilities for “good” forms of variable names, of which we will consider two:
Pothole_case_nameing uses lowercase words separated by underscores _. The underscores make it easier to read the variable. The length of the variable name must be small and understandable. For example, consider the variable temp_celsius, which conveys all the essential information we need while still legible.
CamelCase or CamelCase capitalizes the first letter of words in a variable name to make it easier to read. In some cases, the first letter of the variable may be uppercase. The variable tempCelsius is an example of camelCase or TempCelsius in the case of CamelCase.
Small and targeted methods
Functions are a way to decongest your code from lengthy code sequences. A good practice is to write functions that you already believe are small, even smaller. There is no guideline for how small it should be, but the rule of thumb is to keep it relatively small that a new developer can read it. More specifically, in the last decade, there has been a competition in the Python programming language for who can write multi-line methods in one. As a result, these methods are not widely understood except by those who have reached the level of programming at such a level. For example:
def create_matrix_size_5():
matrix = [] for i in range(5):
# Append an empty sublist inside the list
matrix.append([]) for j in range(5):
arr.append(i)
return arr
def create_matrix_size_5_v2():
matrix = [[j for j in range(5)] for i in range(5)]
These two methods deal with the same object, creating a size five matrix. However, the create_matrix_size_5_v2 () approach is more challenging to understand since it combines a 6-line function into one. And it may not be obvious when you have a slight problem like this, but it will escalate depending on the complexity of the problem.
The complexity of the method should be addressed with simplification. A method can do many things, make tables, call servers, perform operations, etc. In this case, we need to export these functionalities into sub-methods so that each method deals with one thing. For example [4]:
# https://refactoring.guru/extract-method
def printOwing(self):
self.printBanner()
# print details
print("name:", self.name)
print("amount:", self.getOutstanding())
To:
def printOwing(self):
self.printBanner()
self.printDetails(self.getOutstanding())
def printDetails(self, outstanding):
print("name:", self.name)
print("amount:", outstanding)
Consistent Indentation
The indentation is essential due to make our code easy to read. It is crucial when using multiple loops, functions and if statements. The indentation provides you with an excellent visual way to see which commands are outside a loop or if statement. Some languages (for example, Python) require the correct code indent to work. Their functionality depends on the indentation.
There are two acceptable ways to use curly braces. Either way is fine for developers to use as long as they are consistent throughout the program.
The first style is called “Same line”. The “}” bracket must be aligned vertically with the first letter of the word that starts the closing block. In addition, each bracket must be in its code line except for if / else.
function something() {
if (condition()) {
command();
}
}
The second style is called “Newline”. The bracket “}” should line up vertically with the { that it belongs to. Every { and } should be on its line of code.
function something()
{
if (condition())
{
command();
}
}
Commenting & Documentation
As mentioned at the beginning of the article, programming articulates our thinking on a problem. Therefore, it is crucial to explain our steps to reach the solution. IDEs (Integrated Development Environments) and code editors have come a long way in the past few years. The developers and communities work to build plugins that force you to write the documentation of the code.
Commenting on your code is a great way to describe your thoughts. However, like any other thing in the world, when you overdo it, it hurts you.
// US variable
country_US = 'US'
When the text is that obvious, it’s not productive to repeat it within comments. Instead, the comments should ideally explain “why” you did something the way you did. If you need to write more than one line comment to explain the code, you should consider refactoring it to make it more readable.
Read Open-Source Code
Open source projects are created with the help of many developers. These projects must maintain a high level of code readability so that the team can work together as efficiently as possible. So it’s a good idea to browse the source code of these projects to see what these developers are up to. An open-source project can be the CodeIgniter.
Conclusion
In our profession, we work respectfully and effectively with a group of people for a common purpose. Clean code can reduce endless bug sessions, increase productivity and make us better developers. I hope that this article will trigger you to search more about clean and quality code because it matters. Thank you for your reading time.
References:
[1]: Wikipedia, Spaghetti code, <https://en.wikipedia.org/wiki/Spaghetti_code#:~:text=Spaghetti%20code%20is%20a%20pejorative,with%20insufficient%20ability%20or%20experience>.
[2]: Barry Boehm, “A Spiral Model of Software Development and Enhancement”, May 1988, <https://ieeexplore.ieee.org/document/59>
[3]: Robert C. Martin Michael, C. Feathers, Timothy R. Ottinger, Jeffrey J. Langr, Brett L. Schuchert, James W. Grenning, Kevin Dean Wampler, Clean Code: A Handbook of Agile Software Craftsmanship 1st Edition
[4]: Refactoring Guru, Extract Method, <https://refactoring.guru/extract-method>
[5]: Github, CodeIgniter, <https://github.com/bcit-ci/CodeIgniter>