The correct way to define predicates and functions

When defining Predicate or Function , I used them as static final

 private static final Predicate<SomeDto> SOME_PREDICATE = new Predicate<SomeDto>() { @Override public boolean apply(SomeDto input) { return input.isValid(); } } 

However, I noticed that there is a lot of benefit with the enum version enum , for example

 private enum SomePredicate implements Predicate<SomeDto> { INSTANCE; @Override public boolean apply(SomeDto input) { return input.isValid(); } } 

I know about enum vs static final , but are there any real advantages to using enum over static final with predicates or functions?

+5
source share
2 answers

The main advantage of the single-element enum approach in this case is that Predicate / Function automatically Serializable .

For this purpose, for example, Guava itself uses enum for some of its Predicate and Function implementations for this reason. Josh Bloch recommends using enum if you need a singleton in Effective Java 2nd Ed., Point 3 . Quote:

This approach is functionally equivalent to the open-source field approach, except that it is more concise, provides free serialization techniques and provides an excellent guarantee against multiple instances even in the face of complex serialization or reflection attacks. Although this approach has not yet been adopted, a singleton enum type is the best way to implement singleton code.

Guava provides these singletones through static methods in its API, though avoiding the ugliness of SomePredicate.INSTANCE in user code.

+5
source

None of the methods is more correct than the other.

If you read the previous answer in, What is the advantage of renaming Java over a class with public static end fields? , you will see that the enum approach has the advantage that it is easy to iterate over all possible enumeration values. However, in your case you have only one possible value, therefore it is not profitable.

One of the advantages of an enumeration-based approach is that your class will have a prettier name and a name you can choose from. If you want to print the class name, this may be the deciding factor.

0
source

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


All Articles