Otto Émepé
Otto Émepé

Reputation: 29

Java - Alternative to very long switch case

In my Java "Pear" class, I have a huge list of approximately 1000 variables :

public class Pear {

    private String 
    a100, 
    a110, 
    a120, 
    ...
    etc.

}

I need to set each one of these variables based on the given value of a banana, so I had a first basic idea to do it with a switch case :

public class Pear {

    ...

    public void setValues(Banana aBanana) {

        switch (aBanana.getValueName()) {
        case "300886":
            a100 = aBanana.getValue();
            break;

        case "309606":
            a110 = aBanana.getValue();
            break;

        case "300843":
            a120 = aBanana.getValue();
            break;

        /* ...and so on for 1000 variables*/

        }
    }

}

, but I feel like this is not the good way to accomplish this, and this is not going to be very readable neither maintainable. How could I replace this switch case ?

Edit : I think there is a misunderstanding on the call of "setValues". It is going to be called like this (I added some pears) :

public static void main(String[] bananas) {

    Pear pear = new Pear();

    pear.setValues(bananas[0]);
    pear.setValues(bananas[1]);
    pear.setValues(bananas[2]);
    ...etc for 200 times approximately...

}

Upvotes: 0

Views: 1515

Answers (1)

ernest_k
ernest_k

Reputation: 45309

Having hundreds of variables to store multiple values of the same kind is room for bugs and difficult maintenance (which led to this question).

If you changed your data structure, you would get rid of all the unnecessary variable declarations, and you would have logic coded against values (codes), rather than variable names.

A Map is designed to be used to associate keys to values (value names to values, in your case).

Map<String, String> valueMap = new HashMap<>();

public void setValues(Banana aBanana) {
    valueMap.put(aBanana.getValueName(), aBanana.getValue());
}

Now this introduces changes elsewhere, but then that's justified because your typical "read" code would start from the same "value names" too:

public String getValue(String valueName) {
    return this.valueMap.get(valueName);
}

Upvotes: 2

Related Questions