Should predicates in a Utils class be represented as constants or as static methods?

Recently, I have been working with guava predicates and utilities. I created Utils.class, where I store some predicates that I use in different parts of the code. Thus, this problem arose, and we (my colleagues and I) did not agree on this.

What is the correct path or “good practice path” for placing a predicate in a utility class ?, as a constant that defines it using an uppercase letter or a static method ?. Next I write an example:

public final class Utils {

public static final Predicate<Element> IS_SPECIAL = new Predicate<Element>() {
    @Override
    public boolean apply(Element elem) {
        return elem.special;
    }
};


public static Predicate<Element> isSpecial() {
    return new Predicate<Element>() {
        @Override
        public boolean apply(Element elem) {
        return elem.special;
    }}

By the way, guava offers some predicate predicates and provides them as a method that returns predicates, but other libreries do the same as their constants.

+4
4

: API .

API, , . , , , - , .

, . :

  • -. , , . , .
  • rinde, . , .
  • -. , , .
  • , new Predicate<Element> . . , . , , , .

, . (, Utils Elements, Java).

public final class Elements {
  private static enum ElementPredicate implements Predicate<Element> {
    SPECIAL {
      @Override public boolean apply(Element e) { return e.special; }
    }
  }

  public static Predicate<Element> isSpecial() {
    return ElementPredicate.SPECIAL;
  }

  private Elements() {}
}

, , Java 8, , . lambas , , , , , . , isSpecial() Element, , :

Stream<T> stream = ... ;
stream
    .filter(Element::isSpecial)
+7

, : , , , . , : , .

- - : () - . .

+5

, , ...

public final class Utils {    
    private static final Predicate<Element> IS_SPECIAL = new Predicate<Element>() {
        @Override
        public boolean apply(Element elem) {
            return elem.special;
        }
    };

    public static Predicate<Element> isSpecial() {
        return IS_SPECIAL;
    }
}

, ...

+4

isSpecial() , . , IS_SPECIAL.

0

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