How clean is your code? – Standards and ESLint rules

Introduction

Hi, I am Andra and I am a Software Developer at Cegeka Romania. I joined the team 3 and half years ago as RPA developer. Then I turned my attention to projects that have in common Angular (with Typescript) as technology, so this is why the code examples in this article are written in Typescript.

I would say that something which is universal in software development, no matter what technology you chose, are the principles we follow when we are organising and writing the code in order to make it as clear as possible. In this article I will present a part of the rules I take into consideration regarding the code layout.

Before reading this article, please think of the following 3 topics:

  1. How easy it is to understand the code, review it, and revise it months after you write it.
  2. How easy it is for others to read, understand, and modify the code written by you without your support.
  3. How easy it is to modify one line of code without getting other lines modified.

According to Steve McConnell, the Fundamental Theorem of Formatting says that “good visual layout shows the logical structure of the program”. Starting from this statement, I will detail a few of the aspects I pay attention to when I’m writing, reviewing and refactoring code.

1. Indentation

Program Indentation and Comprehensibility study by Richard J. Miara, Joyce A. Musselman, Juan A. Navarro, and Ben Shneiderman, reveals that there is a strong connection between indentation and improved comprehension of the code. They affirm that the subjects of this study found it difficult to work with a program with no indentation at all and they concluded the optimal level of indentation is 2 or 4 spaces.‘

When I read a program, I expect to be able to find out pretty fast where a statement starts and ends. This is not happening to me if I take a quick look over example 1-1. The entire content of the method has 4 spaces indentation while 2 would have been enough. Also, the content of the if statements has another 4 spaces indentation and then, the array elements that compound the recipient.fullName are displayed on separate lines with a lot of indentation which doesn’t improve the readability of this method. On the penultimate line of code, we can observe an indentation of 2 spaces, which is fine, but the problem is when we report to the entire method and that line is not aligned with the others on the same level.

1-1

In contrast to the first example, image 1-2 shows the same method, written a little bit different, but with good indentation, in which all statements are aligned according to the proper level of indentation.

1-2

2. White spaces and blank lines

2.1 White spaces

I won’t say whether it is good or bad to add or not white spaces in certain situations. I will just let you decide by the power of example. Next you can find the same code, the first without ‘optional’ white spaces and the second one with.

2.1 – 1
2.1 – 2

I can strongly affirm that I prefer example 2.1 – 2. It’s much easier to read and understand what this implementation does than in example 2.1 – 1. Indeed, 2.1 – 1 is quite an extreme sample. Maybe there won’t be so many consecutive conditions and statements that are not using empty spaces at all, but at a file level it can happen that lack of empty spaces to make the code harder to read.

Another thing that I would like to mention it’s that the readability of the 2.1 – 2 example is improved not by the fact that I added empty spaces, but also by the organization of a sequence of conditions on multiple lines. Be aware when you do that in order to make sure that you highlight that the statement continues on the next line. In this case, placing the || operator at the end of the line and not at the beginning does that.

2.2 Blank lines

The result of a study claims that there is an optimal number of blank lines to use in a program. 

Steve McConnel affirms in Code Complete as a result of Debugging Effort Estimation using Software Metrics  study by N. Gorla, A.C. Benander, and B.A. Benander that the optimal number of blank lines in a program is about 8 to 16 percent’.

I recognise that I didn’t test the statement for real, but I can say that I am using the blank lines in order to achieve a better grouping in the code (see example 3 – 2). 

But even as much as I like to use them to improve the code readability, I don’t like to abuse of them at all. I don’t think it will bring any benefit to add multiple empty lines instead of one between two areas of code with different purposes or insert a blank line just before the closing curly brace of a method.

3. Grouping

When I think about grouping the code, I think about organising it into chapters. A lot of times I found it quite difficult to follow the steps that a method goes through and that happened because there was no structure. The example 3 – 1 is what I would rather call not an example to follow. It’s not that bad, it can be read and understood, but not as fast as the ones in which the code is grouped by some criteria and separated through empty lines (examples 3 -2).

3 – 1

When I have to structure a method, I take into consideration splitting the code in smaller code portions, each of them having its purpose. In the next example, unlike 3 – 1, first I validate the parameters of the method and treat the shortest case. I find it easier to have an if statement with one line, instead of reading the entire structure to see if in the end exists an else clause. Then I organize the rest of the method in 4 sections: the body, the recipient and sender assignment and the send method call.

3 – 2

4. Parentheses and curly braces

I know that may sound naive because it’s one of the first programming topics that we start with when studying programming, but this is more frequently found in the code than you might think. A single pair of parentheses/curly braces opened or closed in the wrong place or even not used, can change completely the entire behaviour of your code.

4.1 Parentheses

Sometimes we may not need some parentheses, but we use them in order to organise the code better, to make it easier to read. Such an example is the situation when we have multiple logical conditions. Try to compare the following example written in different manners.

4.1 – 1
4.1 – 2

The result of those 2 examples is the same. The difference is that the second one seems more logical just because it’s easier to read by the way it’s organised with the aid of the parentheses that have no role in this implementation but add clarity.

4.2 Curly braces

I’ll start with the most common problem that I found in the code: not using the curly braces when the statement has a single line inside.

4.2 – 1

A while ago, I was working on an application pretty considerable as dimension, started a few years ago, written by multiple developers who didn’t follow the same layout rules. At some moment, a bug in production was assigned to me. So, there was not much time to investigate it or understand the existing code very well. The fix was nothing more than adding a variable assignment in an existing if statement. Simple enough I would say. I added that single line of code and I was surprised to find out the behaviour wasn’t the expected one. Because I’m used to having curly braces even in the situation where a statement has only one line, I didn’t even observe that the curly braces were missing, so I just added the assignment. My luck was that I quickly found the problem. So in the best scenario, you’ll lose very few minutes to figure out what’s the problem, but it’s a loss, not a win.

5. Statement length

The books are saying the proper maximum length for a code line is 80 characters. Exactly how much it fits in a column that could be read vertically, without moving your look to the right and back to the left.

This is debatable in my opinion. Screen resolutions can differ from a programmer to another, but the common thing is that at team level a convention should be established. Whatever code line length that doesn’t make the developer to really horizontally scroll (not just with the eyes), I think it works.

For example, on the current Angular project that I’m working on, we configured the linter to restrict the code line length to 160 characters. Which is double the recommended value. But it’s fine because it’s working for this team and for this kind of project. Actually, 80 could be far too less for the html files we have and the way we are formatting them in this particular case.

Conclusion

The main idea of this article is how to improve the code readability through layout. You should do that for the other developers and for yourself. Even you will thank yourself a few months later if you put in some effort to get used to following some layout rules. At the beginning it can be a little bit difficult, but then it will become a habit.

In conclusion, I want to say that rather than the rules themselves, it’s important to:

Be consistent.

I think that it’s always a good idea to pick some rules, decide how to implement them and stick with them. And in case the project you’re working on has already a considerable size, investigate what conventions are already in place and adapt your coding style to them as much as your own considerations allow you.

Decide the layout rules details at team level and depending on the application you’re working on.

Challenge: Make sure you discuss with your team about the rules to follow and try to agree to some common standards if you don’t have them already set.

Automate as many of the rules as possible.

After you read this article, you might have the impression that you, as a programmer, have to invest a lot of time in making sure that you respect all the rules that are established. Not completely untrue, but far from the real effort estimation. At the moment you decide over a minimum set of rules, allocate some time to configure a linter. Then just make sure you fix all the errors and warnings before commiting your code changes. Some of the eslint configurations related to the topics debated above can be found in the bonus section.

The subject of this article, code layout and the practices that lead to its improvement, is a very subjective one. So, in the end, if you want to debate more on one of the topics in this article or share any rule that you’re using, you can find me on LinkedIn.

Bonus

This is just an enumeration of a few of the eslint rules I use and some examples of how I usually configure them. In order to understand what they are used for and see all the existing options for each rule, see the references to the official eslint documentation.

max-len

Enforces a maximum line length.

How I use it:

“max-len”: [“error”, { “code”: 160 }]

max-depth

Enforces a maximum depth that blocks can be nested.

How I use it:

“max-depth”: [“error”]

indent

Enforces a consistent indentation style.

How I use it:

“indent”: [“error”, 2]

no-multiple-empty-lines

Enforces a maximum number of consecutive empty lines and depending on the other options restrict the number of empty lines at the beginning/end of the file.

How I use it:

“no-multiple-empty-lines”: [“error”, { “max”: 1, “maxEOF”: 1 }]

lines-between-class-members

Enforces the lines between class members.

How I use it:

“lines-between-class-members”: [“error”, “always”, { “exceptAfterSingleLine”: true }]

space-in-parens

Enforces consistent spacing inside of parentheses.

How I use it:

“space-in-parens”: [“error”, “never”]

curly

Enforces that block statements are wrapped in curly braces.

How I use it:

“curly”: [“error”]

brace-style

Enforces consistent brace style for blocks.

How I use it:

“brace-style”: [“error”, “1tbs”, { “allowSingleLine”: true }]
Author avatar
Andra Fecioru

Adaugă un comentariu:

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *