Is it acceptable to pass builder instances around from one object to another to add the different field values?
In the below example, the details to create the VacationPlan instance should be obtained from multiple places (DateAdder and PlaceAdder). The Organizer creates the builder instance and passes that as arguments to these "appender" instances and finally executes the build() call.
Example:
public class Organizer {
private final DateAdder dateAdder;
private final PlaceAdder placeAdder;
private final VacationProviderSearch vacationProviderSearch;
public void organizeVacation() {
VacationPlan.Builder vacationPlanBuilder = VacationPlan.newBuilder();
vacationPlanBuilder = dateAdder.addDate(vacationPlanBuilder);
vacationPlanBuilder = placeAdder.addPlace(vacationPlanBuilder);
VacationPlan vacationPlan = vacationPlanBuilder.build();
List<Provider> providers = vacationProviderSearch.getProviders(vacationPlan);
// use providers to get the best vacation provider
}
}
We were discussing this approach at work and I argued it is better for those individual appenders to accept non-builder instance as arguments and return their respective output as POJOs.
Something like below:
public void organizeVacation() {
VacationDateRange dateRange = dateProvider.getDateRange(userRequestJson);
String location = locationProvider.getLocation(userRequestJson);
VacationPlan vacationPlan = vacationPlanBuilder.newBuilder()
.startDate(dateRange.getStartDate())
.endDate(dateRange.getEndDate())
.location(location)
.build();
List<Provider> providers = vacationProviderSearch.getProviders(vacationPlan);
// use providers to get the best vacation provider
}
This makes sure there are no mutable instances floating around the system. Which of these approaches is better?
Aucun commentaire:
Enregistrer un commentaire