Jesus Zavarce
Jesus Zavarce

Reputation: 1759

We should use constants as descriptive variable name to initialize the default value of some field?

I found an implementation that has this structure (extracted from the book Head First Design Patterns.):

public abstract class Pizza {
    String name;
    String dough;
    String souce;

    List<String> toppings = new ArrayList<>();

    //another methods ....

    public String getName() {
         return name;
    }
 }

Example of concrete class:

public class NYStyleCheesePizza extends Pizza {
    public NYStyleCheesePizza() {
        name = "NY Style Sauce and Cheese Pizza";
        dough = "Thin Crust Dough";
        souce = "Marina Souce";
        toppings.add("Grated Regiano Cheese");
    }
    .......
}

To formulate my question, I did this modification on the concrete class :

 public class NYStyleCheesePizza extends Pizza {
    private static final String DEFAULT_NAME = "NY Style Sauce and Cheese Pizza";
    private static final String DEFAULT_DOUGH = "Thin Crust Dough";
    private static final String DEFAULT_SOUCE = "Marina Souce";

    public NYStyleCheesePizza() {
        name = DEFAULT_NAME;
        dough = DEFAULT_DOUGH;
        souce = DEFAULT_SOUCE;
        toppings.add("Grated Regiano Cheese");
    } 
 ......
}

So, my question is:

We should use constants as descriptive variable name to initialize the default value of some field ?

Upvotes: 0

Views: 373

Answers (1)

jaco0646
jaco0646

Reputation: 17066

The first assumption is that these default values are only used once, otherwise we would want constants for the sake of keeping our code DRY.

Given the aforementioned assumption, the decision to extract a String constant will always be a judgement call, because it's based on the subjective value of the constant's name, in terms of "descriptiveness". Basically, if you feel that DEFAULT_NAME enhances readability versus name (as assigned in the constructor) then by all means, extract the constant. Personally, I find the enhancement very slight in this case; but I will admit that without the constant, I need to combine name with the context of a constructor to derive what the constant conveys explicitly.

What you should never do is this (again assuming a single-use constant).
private static final String NAME = "name";
This constant adds no value in terms of readability, increases the scope of the String unnecessarily, and pollutes the namespace of the class.

Finally, note that String constants are a special case, because their value can communicate their meaning. Other (primitive) constants, such as integers, should probably always be extracted.

Upvotes: 2

Related Questions