Let's say I have few entity classes:
class EntityA { LocalDate date1; LocalDate date2; }
class EntityB { }
class EntityC { LocalDate date1; }
and I want to pass them through some logic containing lots of conditional checks. Simplified version of something like:
public class Predicate {
public boolean test(EntityA a, EntityB b, EntityB c) {
boolean aDate1Valid = isDateValid(a.getDate1());
boolean bExists = b != null;
boolean cExists = c != null;
return (aDate1Valid && bExists && cExists && isDateValid(c.getDate1()))
|| (aDate1Valid && !bExists)
|| (aDate1Valid && !cExists && isDateValid(a.getDate2()));
}
}
currently I'm retrieving all entities in advance before executing the test()
method:
public static void main(String[] args) {
Predicate predicate = new Predicate();
EntityA a = loadEntityAFromDB1();
EntityB b = loadEntityBFromWebService1();
EntityB c = loadEntityCFromWebService2();
predicate.test(a, b, c);
}
The problem is loading all entities is quite expensive (it involves DB queries, few external API calls etc.) and my Predicate's logic doesn't necessarily need to check all of them - for example when isDateValid(a.getDate1())
is not true, then nothing else needs to be checked.
Is there any better way to design this to load required data in more lazy way and to keep my business logic clean from data access logic?