Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferring compile-time constants to enums in some specific cases

Tags:

java

enums

I'm reading J.Bloch's Effective Java and come up with the following (Setcion about enums):

Far fewer enums benefit from associating multiple behaviors with a single method. In this relatively rare case, prefer constant-specific methods to enums that switch on their own values

To me this case of using compile-time constants is not clear. Couldn't you provide a simple example reflecting that?

like image 641
St.Antario Avatar asked Sep 28 '15 07:09

St.Antario


1 Answers

I think what is being discussed in that passage is the comparison between:

void myMethod(MyEnum enum){
    switch(enum){
    case VALUE1:
        break;
    case VALUE2:
        break;
    }
}

and

enum MyEnum{
VALUE1(){
    protected void myMethod(){
        //body
    }
},
VALUE2(){
    protected void myMethod(){
        //body
    }
}
protected abstract void myMethod();
}
like image 122
Spartak Singh Avatar answered Nov 12 '22 03:11

Spartak Singh