Become a clean coder – use storytelling
Writing clean and easy to read code is the benchmark for a good developer. A lot of developers have the mentality to write working code first, then focus on code that looks good. I challenge that mentality because code defects are almost certain to happen, at the very least it is most likely that someone will modify your code one day and when they do they are more likely going to introduce a defect if they do not understand what the code is doing. That is where, what I call, “storytelling” will benefit your code’s readability.
The whole idea is anyone could potentially read your code, ANYONE. Both what it does and its intent. Including non programmers with some basic math understanding. They should still have a basic idea of what is going on based on the naming of your functions. Let’s look at a basic example.
export function drinkBeer(person, beersAvailable) {
if (person.age >= 21) {
return beersAvailable - 1;
} else {
return beersAvailable;
}
}
So if a person is over the age of 21, then consume a beer, otherwise do not. Now look at this example:
function isPersonLegalDrinkingAge(person) {
return person.age >= 21
}
function consumeABeer(beers) {
return beersAvailable - 1;
}
export function drinkBeer(person, beersAvailable) {
if (isPersonLegalDrinkingAge(person)) {
return consumeABeer(beersAvailable);
} else {
return beersAvailable;
}
}
Now this is a basic example, but I am sure you will see that when reading the drinkBeer function you not only see what it does, but what it is supposed to do and why. A more complex example follows the same principles and should be just as easy to read and understand.
You see that the check for the age of 21 is to determine their legal age to drink and the intent of the beersAvailable – 1 code was to remove the amount of beers. So for example, if you needed to make a change to make the legal drinking age different for different countries, then you know what needs to change.
A few guidelines to follow:
- Names should be descriptive as possible without being too long
- Keep functions small, smaller than you may initially want to
- Functions should only do one thing Keep them positive
Through storytelling through code, not only does this make your methods / functions more readable and clear, it shows what you intend to do with it. So if there was a defect found, and the intent of a function was to do something but it was not doing what it described, I will be looking at that as the culprit. Try it on some code. In 6 months time when you have to go back and edit it, you will be glad you did.