Clean Code applied to JavaScript - Part I. Before your start
This post is the first of an interesting series of posts that will delve into the well-known topic that is "Clean Code" but applied to JavaScript.
In this series, we are going to discuss the classic tips around clean code that every programmer should know but applied to a specific JavaScript / TypeScript language.
- Part I. Before your start.
- Part II. Variables.
- Part III. Functions
- Part IV. Comments
- Part V. Exceptions
Introduction
The first thing to do is go over the clean code's concepts:
1. Code smell and refactoring
A code smell is a surface indication that usually corresponds to a deeper problem in the system - Martin Fowler
Bad code smells can be an indicator of factors that contribute to technical debt - Robert C. Martin
In my opinion, Martin Fowler and Robert C. Martin definition's are compatible because Fowler's definition indicates a clue for a software issue while Martin's definition refers to a side-effect caused by code smells.
2. Another interesting term is technical debt:
Technical debt is a concept in software development that reflects the implied cost of additional rework caused by choosing an easy solution now instead of using a better approach that would take longer.
Therefore, as in life itself, the ideal is not to have debts but for this we have to have a healthy economy (experienced programmers and infrastructure that allows developments without negative consequences). However, as in real life, sometimes we need a loan to study at the university or buy our first car, we have that debt under control and we pay it little by little with interest. In the software, it should be exactly the same, we must contract the debts that we can pay later. None of us would think of buying a house of several million without savings and without employment, those are the debts that lead us to failed software.
- So, code refactoring is the process of restructuring existing computer code without changing its external behavior.
- Refactoring improves nonfunctional attributes of the software.
- Advantages include improved code readability and reduced complexity.
- These can improve source-code maintainability.
- Create a more expressive internal architecture to improve extensibility.
Before your start
Before starting to see clean code's examples in JavaScript, it is very important some recommendations that are essential for teamwork.
Readable for humans
The code must be human readable. Do not think about how it will be processed by the computer because there will be many tools that will transform our code (transpilators). Therefore, the most important thing is that the code will be readable by humans because the longest of your work when you are developing code will be reading code instead of writing it.
Below, there are three examples of the same array of users. Which is more readable of the three examples? Which one requires you less intellectual effort to do the reading? Well, that's the way you should structure your code.
const users = [{ id: 1, name: "Carlos Caballero", memberSince: "1997-04-20", favoriteLanguageProgramming: ["JavaScript", "C", "Java"] }, { id: 2, name: "Antonio Villena", memberSince: "2014-08-15", favoriteLanguageProgramming: ["Go", "Python", "JavaScript"] }, { id: 3, name: "Jesús Segado", memberSice: "2015-03-15", favoriteLanguageProgramming: ["PHP", "JAVA", "JavaScript"] } ];
const users = [
{ id: 1, name: "Carlos Caballero", memberSince: "1997-04-20", favoriteLanguageProgramming: ["JavaScript", "C", "Java"] },
{ id: 2, name: "Antonio Villena", memberSince: "2014-08-15", favoriteLanguageProgramming: ["Go", "Python", "JavaScript"] },
{ id: 3, name: "Jesús Segado", memberSice: "2015-03-15", favoriteLanguageProgramming: ["PHP", "JAVA", "JavaScript"] },
];
const users = [
{
id: 1,
name: "Carlos Caballero",
memberSince: "1997-04-20",
favoriteLanguageProgramming: ["JavaScript", "C", "Java"],
},
{
id: 2,
name: "Antonio Villena",
memberSince: "2014-08-15",
favoriteLanguageProgramming: ["Go", "Python", "JavaScript"],
},
{
id: 3,
name: "Jesús Segado",
memberSince: "2015-03-15",
favoriteLanguageProgramming: ["PHP", "JAVA", "JavaScript"],
}
];
Develop in English
I am not an English speaker, in fact, my big problem in this industry is that I can barely have good and interesting conversations in English compared to my native language. However, in class I transmit to my students that they must write code in English and, consequently, all my code is developed in English. It is better to use bad English than to use your mother tongue, unless you are fortunate to be an English speaker. The reason for this is that English is used for business worldwide. You may like it or not, but everyone in the world understands that English is the language to use when interacting with another country and, as I told you before, most of your time you will be reading code. Imagine reading code in a language that you will not be able to know the variables or function's name, all the code will be encrypted for you.
Therefore, you must develop in English even if it is not your native language. We will be learning English as we work. In any case, think of me, I'm not native but every day I read and write English, of course with mistakes but we must all be understandable to each other because the important thing when using a language is making our meaning across.
Try to deduce what the following code snippet does, something very basic in a language of yours. That is, the following code snippet is in different languages and in English (obviously if one of the sample languages is your native one, you will understand). In any case, if you are a polyglot, go to google translate and put the code in another language that you don't know and try to deduce what the code does.
const benutzer = {
id: 1,
name: "John Smith",
mitgliedVon: "1997-04-20",
};
Gehaltserhöhung(benutzer, 1000);
const użytkownik = {
id: 1,
imię: "John Smith",
członekZ: "1997-04-20",
};
wzrostWynagrodzeń(użytkownik, 1000);
const user = {
id: 1,
name: "John Smith",
memberSince: "1997-04-20",
};
increaseSalary(user, 1000);
Teamwork
Once upon a time there was a programmer developing a software project... What a beautiful story! This is how we all learn to develop software, alone. We face a computer typing code and solving problems but today nobody develops software alone.
Therefore, we have to think about working in a team. Eternal discussions among junior programmers:
- Tabulate using space or tab.
- Open keys next to the name of the function or a lower line.
- Put a semicolon at the end of a sentence.
Do those arguments sound to you? Sorry, those discussions are absurd because those decisions are agreed between all team members and then development tools that modify the code and normalize it to everyone are used.
A team of developers is integrated at the moment when a programmer opens a project file and starts reading the code, and he is not able to deduce if that code has been programmed by him or by a teammate. This is the perfect team development point, we have become a single great programmer working together. I remind you that if we have to know who has written something of the code we have powerful tools such as GIT.
Therefore, to get to work in a team directly we need:
Not being obliged to use a specific IDE, for this there is the standard .editorconfig that allows us to work each team member with their perfect IDE. Each person is a world, and not everyone should use WebStorm, VSCode or Eclipse because someone decided it by existing a standard that allows us to configure basic structuring elements such as the .editorconfig standard.
.editorconfig helps developers define and maintain consistent coding styles between different editors and IDEs.
root = true
[*]
end_of_line = lf
insert_final_newline = true
[*.{js,py}]
charset = utf-8
[*.py]
indent_style = space
indent_size = 4
[Makefile]
indent_style = tab
[*.js]
indent_style = space
indent_size = 2
[{package.json,.travis.yml}]
indent_style = space
indent_size = 2
The lint allow us to find errors in the formatting of the code based on some rules that we establish and each language has its own Lint, look in your development language and you must configure it among all and use them all. The agreements are the same, sometimes there will be projects in which the code is not done as you like it but at least you can continue typing it that way and delegate to the IDE the person in charge of changing it so that it does not pose a problem to you Time to generate code.
{
"globals": {
"myModule": true
},
"env": {
"browser": true
},
"rules": {
"no-unused-vars": "error",
"quotes": ["warning", "double"]
}
}
const a = 'a';
const b = a;
const c = b;
There is a tool widely used in the industry known as Prettier that allows to change the formatting of our code in real time (plugins of the IDEs) based on the rules of the linter. This allows us to focus on the problem that we have to solve and, in addition, we are generating clean code by being a united team.
Conclusions
In this post we have summarized several fundamental points before trying to address clean code practices and recommendations. The principles we have discussed are general for any developer:
- Write readable code for humans and not for machines. Most of the time you will be reading code, both yours and your partner's.
- Write in English. Today is the international language and we have to be international because that way we can share code with anyone in the world.
- Work in team. Create common rules and rely on tools that allow you to generate code uniformly for everyone. You have to get to the point where the whole project seems programmed by a single person instead of seeing the different customs of the different members of the development team.