Hi, in this article we will shed the light on an important topic.
Every programmer knows how to sort an array, how to balance a tree, how to create and use complex data structures, or event how to convert business specifications to a working code.
BUT.
Are all programmers aware of the importance of writing a good readable code? I bet the answer is a big NO.
Let's take an example of a code I came across while ago, when I was reviewing a merge request submitted by a colleague :
public static int get(Person p) {
return Period.between(p.getBirthDate(), LocalDate.now()).getYears();
}
The above code computes the age of a given person, it is flawless and gets the results correctly, but to understand that, it requires more effort and maybe you will have to dig into more details, or maybe ask your friend about the intention of a such code snippet.
Below a suggestion to re-write the same code, but in a more understandable way :
public static int calculateAgeOfAPerson(Person person) {
LocalDate now = LocalDate.now();
Period difference = Period.between(person.getBirthDate(), now);
return difference.getYears();
}
It is obvious now, that the intention of this snippet is clear as it is described by the code itself, no documentation is required, and the idea becomes clear without the need of going further into the details.
Top comments (0)