Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 10, 2022 11:01 pm GMT

Writing better code

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.


Original Link: https://dev.to/mustabelmo/writing-better-code-ikm

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To