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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

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

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay