I am breaking my head with how to get rid of semantic duplication(Code that is syntactically the same but does different things).
I can't find anywhere a post or something that mentions a bit how to refactor this kind of duplication. All I found was this:
Duplicate Code and Ceremony in Java but it does not go into detail on how to refactor it.
This is the code that is causing me problem:
public class TeamValidator {
public boolean isThereALeader(List<Member> team) {
Iterator<Member> iterator = team.iterator();
while(iterator.hasNext()) {
Member member = iterator.next();
String role = member.getRole();
if(role.equals("Leader"))
return true;
}
return false;
}
public boolean areThereAtLeast2NewJoiners(List<Member> team) {
int amountOfNewJoiners = 0;
for(Member member:team) {
if(amountOfNewJoiners == 2)
return true;
DateTime aMonthAgo = DateTime.now().minusMonths(1);
if(member.startingDate().isAfter(aMonthAgo)) {
amountOfNewJoiners++;
}
}
return false;
}
}
In these two methods there is semantic duplication, because both iterate a list and also check some condition/s. Any idea how could I make this semantic duplication disappear?
I would really appreciate some tip or suggestion on how to refactor this.
false
. \$\endgroup\$candidate.getRole().equals("Leader");
should becandidate.isRole("Leader")
. \$\endgroup\$amountOfNewJoiners
gets incremented whenmember
is the last item inteam
.) \$\endgroup\$.filter()
is all that would be needed here. \$\endgroup\$