Clean Code: Nomi Parlanti e Significativi [2/12]

Clean Code: Nomi Parlanti e Significativi [2/12]

L'importanza dei Nomi Parlanti

Come esseri umani, siamo programmati per comprendere il linguaggio naturale più facilmente rispetto a simboli o abbreviazioni criptiche. Per questo, un codice con nomi ben scelti è molto più comprensibile e semplice da mantenere. In un team, i nomi parlanti migliorano la comunicazione e riducono drasticamente i fraintendimenti.

"Un nome ben scelto è la prima forma di documentazione del codice e rende inutili i commenti"

Immagina di trovarti di fronte a questo codice JAVA:

int x = calculate(a, b);

Il suo scopo è oscuro e richiede di leggere l'intero contesto per essere compreso. Ora confrontalo con:

int totalRevenue = calculateMonthlyRevenue(currentMonth, previousMonth);

Il significato diventa immediatamente chiaro: il codice calcola le entrate totali mensili basandosi su due periodi. Questo semplice cambiamento di nome riduce il carico cognitivo per chi legge.

Principi per Scegliere Nomi Efficaci

1. Esprimere l'intento

Il nome di una variabile, funzione o classe deve comunicare chiaramente il suo scopo.

// Nome poco chiaro

String d;

// Nome chiaro

String deliveryDate;

2. Evitare abbreviazioni criptiche

Abbreviazioni come cnt o tmp possono confondere. Scegli sempre nomi completi e descrittivi.

// Nome complicato 

int cnt = 42;

// Nome descrittivo

int customerCount = 42;

3. Usare un linguaggio coerente

Mantieni un vocabolario uniforme in tutto il progetto. Ad esempio se utilizzi "customer" in una parte del codice, non cambiare improvvisamente con "client".

4. Evitare informazioni ridondanti

Evita nomi che contengono informazioni ovvie o inutili.


// Nome ridondante

String customerString;

// Nome pulito

String customer;

5. Specificità

Sii specifico nei nomi per evitare ambiguità.

// Nome ambiguo

int size;

// Nome specifico

int fileSize;

**
**Ora che abbiamo visto i 5 principi chiave, scopriamo i …

Nomi Parlanti per Funzioni

Le funzioni devono essere nominate in modo che riflettano ciò che fanno. 

Come regola di base da ricordare: “Inizia sempre con un verbo per indicare l'azione svolta”

// Nome poco chiaro

void data();

// Nome parlante

void fetchCustomerData();

Se una funzione restituisce un valore booleano, invece conviene utilizzare prefissi come is, has, can, ecc.

// Nome non chiaro

boolean valid();

// Nome parlante

boolean isValid();

Nomi Parlanti per Classi

Le classi devono rappresentare chiaramente l'entità o il concetto che modellano. 

Solitamente come regola possiamo ricordare di usare nomi al singolare per oggetti e al plurale per collezioni.

// Nome poco chiaro

class Data;

// Nome parlante

class Customer;

// Collezione di clienti

class Customers;

Se la classe rappresenta un'azione o una funzionalità, utilizza un suffisso che ne indichi lo scopo. Esempio: 

// Nome poco chiaro

class Process;

// Nome parlante

class PaymentProcessor;

Esempio Completo:

**PRIMA: **

public class A {

    public int x(List<Integer> y) {

        int s = 0;

        for (int z : y) {

            s += z;

        }

        return s;

    }

}

DOPO:

public class Calculator {

    public int calculateSum(List<Integer> numbers) {

        int sum = 0;

        for (int number : numbers) {

            sum += number;

        }

        return sum;

    }

}

La differenza è evidente: il secondo codice è immediatamente leggibile e comprensibile anche senza ulteriori spiegazioni.


Concludiamo:

Scegliere nomi parlanti è il primo passo per scrivere codice chiaro e leggibile. 

Un codice ben nominato non ha bisogno di commenti superflui perchè si spiega da solo. 

Ricorda sempre che:

" Non scriviamo codice solo per noi stessi, ma anche per chi verrà dopo di noi "

Nel prossimo articolo, esploreremo Funzioni con Uno Scopo, per comprendere come creare metodi semplici, precisi e focalizzati su un unico compito.


The Importance of Speaking Names

As humans, we are programmed to understand natural language more easily than cryptic symbols or abbreviations. Therefore, a code with well-chosen names is much more understandable and easier to maintain. In a team, speaking names improve communication and drastically reduce misunderstandings.

"A well-chosen name is the first form of code documentation and makes comments unnecessary"

Imagine you are faced with this JAVA code:

int x = calculate(a, b);

Its purpose is obscure and requires reading the entire context to understand. Now compare it to:

int totalRevenue = calculateMonthlyRevenue(currentMonth, previousMonth);

The meaning becomes immediately clear: the code calculates total monthly income based on two periods. This simple name change reduces the cognitive load for the reader.

Principles for Choosing Effective Names

  1. Express the intent

The name of a variable, function, or class should clearly communicate its purpose.

// Unclear name

String d;

// Clear naming convention

String deliveryDate;

2. Avoid cryptic abbreviations

Abbreviations like cnt or tmp can be confusing. Always choose complete and descriptive names..

// complicated name 

int cnt = 42;

// descriptive name

int customerCount = 42;

3. Use consistent language

Maintain a consistent vocabulary throughout the project. For example, if you use "customer" in one part of your code, don't suddenly change it to "client".

4. Avoid redundant information

Avoid names that contain obvious or unnecessary information.


// redundan name

String customerString;

// clean name

String customer;

5. Specificity

Be specific in your names to avoid ambiguity.

// ambiguous name

int size;

// specific name

int fileSize;

**
Now that we have seen the 5 key principles, let's discover the …

Speaking Names for Functions

Functions should be named to reflect what they do.

As a basic rule to remember: “Always start with a verb to indicate the action performed”

// unclear name

void data();

// expressive name

void fetchCustomerData();

If a function returns a Boolean value, it is better to use prefixes such as is, has, can, etc. instead.// unclear name

boolean valid();

// expressive name

boolean isValid();

Speaking Names for Classes

Classes must clearly represent the entity or concept they model.

As a general rule, we can remember to use singular nouns for objects and plural nouns for collections.

// unclear name

class Data;

// expressive name

class Customer;

// lcustomer collection

class Customers;

If the class represents an action or functionality, use a suffix that indicates its purpose. Example:

// unclear name

class Process;

// expressive name

class PaymentProcessor;

A Complete Example

**First: **

public class A {

    public int x(List<Integer> y) {

        int s = 0;

        for (int z : y) {

            s += z;

        }

        return s;

    }

}

Later:

public class Calculator {

    public int calculateSum(List<Integer> numbers) {

        int sum = 0;

        for (int number : numbers) {

            sum += number;

        }

        return sum;

    }

}

The difference is clear: the second code is immediately readable and understandable even without further explanations.


Let's Conclude:

Choosing meaningful names is the first step to writing clear and readable code.

A well-named code does not need superfluous comments because it explains itself.

Always remember that:

" We do not write code only for ourselves, but also for those who will come after us "

In the next article, we will explore functions with a purpose to understand how to create simple, precise and focused methods for a single task.