5

When defining Predicate's or Function's, I used to create 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 have noticed that there is a lot of use also with enum version, for example

private enum SomePredicate implements Predicate<SomeDto> {
        INSTANCE;

        @Override
        public boolean apply(SomeDto input) {
            return input.isValid();
        }
    }

I am aware about the enum vs static final topics, but is there any real advantage of using enum's over static final with predicates or functions?

Community
  • 1
  • 1
vtor
  • 8,989
  • 7
  • 51
  • 67
  • 1
    I am not sure about the advantages but there is a disadvantage from a readability point of view, `SOME_PREDICATE.apply(input)` is cleaner than `SomePredicate.INSTANCE.apply(input)`. Again, this is just me and not everyone will find a problem with the readability of the enum approach. – Chetan Kinger Mar 20 '15 at 18:18

2 Answers2

5

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

Guava itself uses enums for some of its Predicate and Function implementations for this reason, among others. Josh Bloch recommends the use of enums when you want a singleton in Effective Java 2nd Ed., Item 3. To quote:

This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Guava exposes those singletons through static methods in its API though, avoiding the ugliness of SomePredicate.INSTANCE in user code.

ColinD
  • 108,630
  • 30
  • 201
  • 202
0

Neither of the ways is more correct than the other.

If you read the previous answer at What's the advantage of a Java enum versus a class with public static final fields? you'll see that the enum approach has the advantage that it's easy to iterate over all possible values of the enum. However, in your case you have only one possible value, so this is not a benefit.

One advantage of the enum-based approach is that your class will have a prettier name and a name you can choose. In case you want to print the name of the class, this might be a deciding factor.

Community
  • 1
  • 1
juhist
  • 4,210
  • 16
  • 33