DEV Community

Cover image for Writing better code
Mustapha Belmokhtar
Mustapha Belmokhtar

Posted on

4 1

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();
    }
Enter fullscreen mode Exit fullscreen mode

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();
    }
Enter fullscreen mode Exit fullscreen mode

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay