Java Clean Code – What to Do with Long Variable Names?

clean codejavaprogramming practices

First example:

countryRepository.getCountriesFromAsiaWhereAreTheMostPlanesAndBoats();
countryRepository.getCountriesFromAfricaWhereAreTheMostCars();

Are these names too big? How else do we call these functions?

I was thinking about parameters, but according to Martin Fowler, it's better not to use parameters in functions.

Second example:

I have to use these two variables in the class:

public static class CompareCountries {     
    public String[] countriesFromAsiaWhereAreTheMostPlanesAndBoats;
    public String[] countriesFromAfricaWhereAreTheMostCars;

    public CompareCountries (String countriesFromAsiaWhereAreTheMostPlanesAndBoats, String[] countriesFromAfricaWhereAreTheMostCars){
        this.countriesFromAsiaWhereAreTheMostPlanesAndBoats = countriesFromAsiaWhereAreTheMostPlanesAndBoats;
        this.countriesFromAfricaWhereAreTheMostCars = countriesFromAfricaWhereAreTheMostCars;
    }   

    public static String[] compares() {}
}

Here the more I can not use parameters.

Best Answer

Never let a code layout style issue motivate you to shorten a name:

public static class CompareCountries {     
    public String[] countriesFromAsiaWhereAreTheMostPlanesAndBoats;
    public String[] countriesFromAfricaWhereAreTheMostCars;

    public CompareCountries (
            String[] countriesFromAsiaWhereAreTheMostPlanesAndBoats, 
            String[] countriesFromAfricaWhereAreTheMostCars
    ) {
        this.countriesFromAsiaWhereAreTheMostPlanesAndBoats =
            countriesFromAsiaWhereAreTheMostPlanesAndBoats
        ;
        
        this.countriesFromAfricaWhereAreTheMostCars = 
            countriesFromAfricaWhereAreTheMostCars
        ;
    }   

    public static String[] compares() {}
}

However, always try to get the point quickly and effectively. Never permit pointless fluff.

Consider:

asianContriesWithMostPlanesAndBoats
africanCountriesWithMostCars

Also, I find it surprising that a class whose responsibility is to "compare countries" only deals with Asia and Africa. The class name might need to be longer. I shouldn't be surprised when I look inside.

Related Topic