Purpose of Functional Interfaces in Java8

前端 未结 3 1068
粉色の甜心
粉色の甜心 2021-01-06 01:22

I\'ve come across many questions in regards of Java8 in-built Functional Interfaces, including this, this, this and this. But all ask about \"why only one m

3条回答
  •  星月不相逢
    2021-01-06 01:56

    Obviously you can skip using these new interfaces and roll your own with better names. There are some considerations though:

    1. You will not be able to use custom interface in some other JDK API unless your custom interface extends one of built-ins.
    2. If you always roll with your own, at some point you will come across a case where you can't think of a good name. For example, I'd argue that CheckPerson isn't really a good name for its purpose, although that's subjective.

    Most builtin interfaces also define some other API. For example, Predicate defines or(Predicate), and(Predicate) and negate().

    Function defines andThen(Function) and compose(Function), etc.

    It's not particularly exciting, until it is: using methods other than abstract ones on functions allows for easier composition, strategy selections and many more, such as (using style suggested in this article):

    Before:

    class PersonPredicate {
      public Predicate isAdultMale() {
        return p -> 
                p.getAge() > ADULT
                && p.getSex() == SexEnum.MALE;
      }
    }
    

    Might just become this, which is more reusable in the end:

    class PersonPredicate {
      public Predicate isAdultMale() {
        return isAdult().and(isMale());
      }
    
      publci Predicate isAdultFemale() {
        return isAdult().and(isFemale());
      }
    
      public Predicate isAdult() {
        return p -> p.getAge() > ADULT;
      }
    
      public Predicate isMale() {
        return isSex(SexEnum.MALE);
      }
      public Predicate isFemale() {
        return isSex(SexEnum.FEMALE);
      }
      public Predicate isSex(SexEnum sex) {
        return p -> p.getSex() == sex;
      }
    }
    

提交回复
热议问题