View Javadoc
1   package epam.legalage;
2   
3   import java.time.Clock;
4   import java.time.LocalDate;
5   import java.time.Period;
6   import java.util.function.Predicate;
7   
8   /**
9    * A predicate that checks if a user is over 18 years old based on their date of birth.
10   */
11  public final class LegalAgePredicate implements Predicate<LocalDate> {
12  
13      private static final int LEGAL_AGE = 18;
14      private final Clock clock;
15  
16      /**
17       * Creates a LegalAgePredicate with the system default clock.
18       */
19      public LegalAgePredicate() {
20          this(Clock.systemDefaultZone());
21      }
22  
23      /**
24       * Creates a LegalAgePredicate with the specified clock.
25       *
26       * @param clock the clock to use for calculating the current date
27       */
28      public LegalAgePredicate(Clock clock) {
29          this.clock = clock;
30      }
31  
32      /**
33       * Tests if the user with the given date of birth is over 18 years old.
34       *
35       * @param dateOfBirth the user's date of birth
36       * @return true if the user is over 18 years old, false otherwise
37       */
38      @Override
39      public boolean test(LocalDate dateOfBirth) {
40          var currentDate = LocalDate.now(clock);
41          var age = Period.between(dateOfBirth, currentDate).getYears();
42          return age >= LEGAL_AGE;
43      }
44  }