Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify method in an Enum class in Java

Tags:

java

enums

I have a class that contains an Enum to do calculation. Each Enum uses some or all of the non-static variables from the outer class. However since they can't access instance variable, I have to pass in them as parameters.

public class Outer{
    ClassA a;
    ClassB b;
    ClassC c;
    Map<MyEnum,Double> results= new EnumMap(MyEnum.class);
    private enum MyEnum{
        X{  public double calc(ClassA _a){ dostuff }           },
        Y{  public double calc(ClassB _b,ClassC _c){ dostuff } },
        Z{  public double calc(ClassA _a,ClassB _b){ dostuff } };
    }

    public void doCalc(){
        for(MyEnum item:MyEnum.values()){
            result.get(item) = item.calc(...);//Not uniform here
        }
    }
}

My problem is that I can't have a uniform way to pass in the parameters in the for-loop. I could make each Enum method takes all classes like

public double calc(ClassA _a,ClassB _b,ClassC _c){ dostuff}

But if I have more classes, the parameter will look too ugly. Is there a better way to do this kind of thing?

like image 540
Wei Shi Avatar asked Jul 01 '11 18:07

Wei Shi


1 Answers

Why don't you pass the instance of outer to the calc() method. In that case, each specific enum will have the logic to deal with the Outer object accordingly and new enums wouldn't require any change.

class Outer {

    ClassA a;
    ClassB b;
    ClassC c;
    Map<MyEnum,Double> results= new EnumMap<MyEnum, Double>(MyEnum.class);
    private enum MyEnum{
        X{  public void calc(Outer o){ }           },
        Y{  public void calc(Outer o){  } },
        Z{  public void calc(Outer o){ } };
        abstract void calc(Outer o);
    }

    public void doCalc(){
        for(MyEnum item:MyEnum.values()){
            item.calc(this);
        }
    }
}


class ClassA {}
class ClassB {}
class ClassC {}
like image 64
Sanjay T. Sharma Avatar answered Sep 25 '22 18:09

Sanjay T. Sharma