There's a potential bug in your method if the user is born just the day after the age requirement. Your method will return true
when it should in fact return false
. For example the following code prints true
:
public static void main(String[] args) {
DateTime test = new DateTime().minusYears(1).plusDays(1);
System.out.println(isUser18Older(test, 1));
}
public static boolean isUser18Older (DateTime userDob, int minimumAge){
DateTime minAge = new DateTime();
Days days = Days.daysBetween(userDob, minAge.minusYears(minimumAge));
return days.getDays()>=0 ;
}
although the user was born the day after the requirement. This is because you're not taking the time into account.
The name of the method is misleading with regard to what it does. It is named isUser18Older
, which implies that the method checks whether a user has at least 18 years-old. However, the method takes a minimumAge
parameter, which is actually the minimum age requirement. Therefore, I suggest renaming that method hasAgeRequirement
.
The code itself could be written more simpler and to-the-point. Instead of getting the number of days between the two dates, just retrieve the number of years between the date of birth and today and compare it with the age requirement:
public static boolean hasAgeRequirement(DateTime userDob, int minimumAge) {
DateTime now = new DateTime();
Years age = Years.yearsBetween(userDob, now);
return age.getYears() >= minimumAge;
}
This is easier to read since it directly codes the intent of the method.
minusYears
method, you'll have to post that code here along with what improvements you are looking to make. \$\endgroup\$