Komplexes Beispiel von funktionale Interfaces in Java

Words
72
Reading
1 min
3y
Listen to this post
~1 min

Abschließend zum Thema funktionale Interfaces in Java, soll dieses Beispiel ein etwas komplexeren Zusammenhang demonstrieren wie man funktionale Interfaces verwenden kann.
Dafür wird für eine Person eine email und Telefonnummer überprüft. Die email muss ein @ enthalten und die Telefonnummer mit 0 beginnen.
Dann werden mithilfe des RegistrationValidator eine Reihe von Lambda Expressions in Validator ausgeführt, um so zu sehen ob eine email und Telefonnummer das vorgegebene Muster erfüllen.

Person

package functional;

/** Simple Person */
public class Person {
    public String email;
    public String phonenumber;

    public Person(String email, String phonenumber){
        this.email = email;
        this.phonenumber = phonenumber;
    }
}

Validator

package functional;
import static functional.RegistrationValidator.*;

public class Validator {

    public static void main(String[] args){
        Person person = new Person("[email protected]","+01465518893");

        /* complex example how functional programming works in java */
        /* examine if email and phonenumber from the created person have the right pattern */
        ValidationResult result = isEmailValid()
        .and(isPhoneNumberValid())
        .apply(person);

        if (result != ValidationResult.SUCCESS){
            throw new IllegalStateException(result.name());
        } else {
            System.out.println(result);
        }
    }
    
}

RegistrationValidator

package functional;

import java.util.function.Function;
import static functional.RegistrationValidator.*;
import static functional.RegistrationValidator.ValidationResult.*;

@FunctionalInterface
public interface RegistrationValidator extends Function<Person, ValidationResult> {

        static RegistrationValidator isEmailValid() {
            return person -> person.email.contains("@") ? SUCCESS : EMAIL_INVALID;
        }

        static RegistrationValidator isPhoneNumberValid() {
            return person -> person.phonenumber.startsWith("+0") ? SUCCESS : PHONENUMBER_INVALID;
        }

        default RegistrationValidator and (RegistrationValidator other) {
            return person -> {
                ValidationResult result = this.apply(person);
                return result.equals(SUCCESS) ? other.apply(person) : result;
            };
        }

        enum ValidationResult {
            SUCCESS, EMAIL_INVALID, PHONENUMBER_INVALID;
        }
    }

Komplexes Beispiel von funktionale Interfaces in Java | Ecency