Is there a reason to override methods in enums in Java 8

As stated here , lambdas provides a fairly elegant way of specifying behavior for individual enumeration values.

Prior to Java 8, I would usually implement this as:

enum Operator { TIMES { public int operate(int n1, int n2) { return n1 * n2; } }, PLUS { public int operate(int n1, int n2) { return n1 + n2; } }; public int operate(int n1, int n2) { throw new AssertionError(); } } 

Now I prefer to use:

 enum Operator { TIMES((n1, n2) -> n1 * n2), PLUS((n1, n2) -> n1 + n2); private final BinaryOperator<Integer> operation; private Operator(BinaryOperator<Integer> operation) { this.operation = operation; } public int operate(int n1, int n2) { return operation.apply(n1, n2); } } 

It seems much more elegant.

I can’t think of the reason for overriding methods for a specific enumeration value now. So my question is, is there any good reason to use method overrides in enum now, or should a functional interface be preferred?

+6
source share
1 answer

If you look at this answer , which outlines the benefits of using the lambda expression in this enum script, you may notice that these benefits all disappear in the pre-Java 8 option. This is no more readable than the old specialized version of enum , and it does not improve performance. In addition, interface BinaryOperator did not exist before Java 8, so its another class that you will need to add to your code base in order to follow this approach.

The main reason for using this approach for delegates in pre-Java 8 code is to make porting easier if you plan to upgrade to Java 8 soon.


Update your updated question:

If you mainly focus on the use case of Java 8, I would recommend always using the delegation approach, when all cases of enum have different behavior, which still follows a similar pattern, which may benefit from using lambda expressions, since its case when implemented operators, as in your example.

A counter-example would be enum , where most of them have common behavior that will be overridden for only one or more cases. For instance:.

 enum Tokens { FOO, BAR, BAZ, AND, A, LOT, MORE // etc … /** Special Token End-Of-File */ EOF { @Override public boolean matches(String input, int pos) { return input.length()==pos; } }; // all ordinary tokens have the same behavior public boolean matches(String input, int pos) { return input.length()-pos >= name().length() && input.regionMatches(pos, name(), 0, name().length()); } } 
+5
source

Source: https://habr.com/ru/post/981868/


All Articles