tags:

views:

150

answers:

2

I'm looking for an elegant way to use values in a Java enum to represent operations or functions. My guess is, since this is Java, there just isn't going to be a nice way to do it, but here goes anyway. My enum looks something like this:

public enum Operator {
    LT,
    LTEQ,
    EQEQ,
    GT,
    GTEQ,
    NEQ;

    ...
}

where LT means < (less than), LTEQ means <= (less than or equal to), etc - you get the idea. Now I want to actually use these enum values to apply an operator. I know I could do this just using a whole bunch of if-statements, but that's the ugly, OO way, e.g.:

int a = ..., b = ...;
Operator foo = ...; // one of the enum values
if (foo == Operator.LT) {
    return a < b;
}
else if (foo == Operator.LTEQ) {
    return a <= b;
}
else if ... // etc

What I'd like to be able to do is cut out this structure and use some sort of first-class function or even polymorphism, but I'm not really sure how. Something like:

int a = ..., b = ...;
Operator foo = ...;
return foo.apply(a, b);

or even

int a = ..., b = ...;
Operator foo = ...;
return a foo.convertToOperator() b;

But as far as I've seen, I don't think it's possible to return an operator or function (at least, not without using some 3rd-party library). Any suggestions?

A: 
int a = ..., b = ...;
Operator foo = ...;
return foo.apply(a, b);

it is possible to do this if foo is object and Operator is base class and concrete operators are concrete classes that implement apply.

Andrey
Could you clarify that?
Matt Ball
you have abstract class "Operator" that has single method apply. there are subclasses like LessOrEqualTo that implement apply(a, b) { return a <= b; }
Andrey
+3  A: 

Not only is this possible, it's used as an example in the frequently referenced Effective Java, Second Edition by Josh Bloch. I don't want to step on his copyright, will look for a similar example online...

Okay, the code I remembered is freely available at the website I linked earlier. Click "Download the code samples used in this book", then look at effective2/examples/Chapter6/Item30/Operation.java.

Lord Torgamus
the code is sooo weird. my java is too low to understand it without comments.
Andrey
Is there a specific part that confuses you? There _are_ a lot of concepts going on there, so explaining the whole thing is kind of out of scope for one SO post.
Lord Torgamus
Check out http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html.
Shakedown
That's pretty awesome. I think that will work perfectly.
Matt Ball