简体   繁体   中英

Enum-getter vs. Getter for each stat

I am currently processing a huge data input, including a lot of values, which I want to receive in getters for later use.

After writing a few methodes, I wondered if it might be a better idea to just use one get Method, with an enum-class containing all possible values, eg

public double getStat(StatType st) {
    if(st != null)
        return st.getValue();
}

instead of

public double getAvgReflection() {
    return ...
}

public double getMaxLifesteal() {
    return ...
}

Is there any convention for using either of the two possibilities? Any dis/advantages?

Thanks in advance!

Using an Enum maxes it easier to add new stats, just add a constant in the Enum. But all stats need to behave the same way, ie be doubles in your example. What happens if you want to add an int stat?

The "convention" you are asking about really boils down to the use and definition of your values. When you make the values Enums, then you must handle them as that type . Meaning, the fields in your class would have to be defined as such:

private MyEnum avgReflection;
private MyEnum maxLifesteal;
...
public MyEnum getAvgReflection {
    return this.avgReflection;
}

And so forth.

Now, you could have your Enums return double values, but these values are static. I don't think you are concerned about static values, but, instead, perhaps a static set of values.

You then have two possible options: declare all possible parameters as fields, or create one aggregate field to hold all values and then use an Enum as an index:

public enum MyEnum {
    averageReflection(0),
    maximumLifeSteal(1);
    private int value;
    private MyEnum(int value) {
        this.value = value;
    }
    public int getValue() {
        return this.value;
    }
}
...
private double[] attributes = new double[100]; // arbitrary initialization
public double getAttribute(MyEnum attribute) {
    return this.attributes[attribute.getValue()];
}

The two restrictions on using an array (assuming you want primitive values and you are concerned about performance) is that all the values must be the same type, and the number of attributes will be set at compile time.

Additionally, you may just want to use a Map<String,double> or Map<MyEnum,double>, or even Map<MyEnum, Object>. A Map type will give you the ability to maintain a dynamically-sized set and possibly holding multiple types as well (with the costly overhead of converting your values).

You should base your decision on the amount of attributes you need to keep, the kind of overhead you are willing to tolerate, and your style.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM