I've been running into a common pattern when requesting data from multiple sources:
Have a list of objects from one source (e.g. a list of
Cars) with anidproperty and a few other properties populated (e.g.make,model,year).Call some service (second source) with the list of
Carids to get data for a few otherCarproperties (e.g.lastOwner,lastPurchasedDate). The service returns list ofCarSupplementalDatas that have theCar'sid,lastOwner,lastPurchaseDate.Add data from the service (second source) to the object from the first (e.g. the
CarSupplementalDatato theCardata by:)for (Car car : cars) { for (CarSupplementalData supplemental : supplementals) { if (car.getId() == supplemental.getCarId()) { car.setLastOwner(supplmental.getLastOwner()); car.setLastPurchaseDate(supplmental.getLastPurchaseDate()); } } }
The problem is that this boilerplate code / pattern is repeated many times in my application. Ideally, I would like to get rid of the nested looping and checking if ids match.
The only way I know to eliminate the inner looping and id matching is to change the service (second source) to take only one Car id:
for (Car car : cars) {
CarSupplementalData supplemental = carSupplementalService.getData(car.getId());
//I know I have the supplemental data for this car. No id matching needed.
car.setLastOwner(supplmental.getLastOwner());
car.setLastPurchaseDate(supplmental.getLastPurchaseDate());
}
When performance is not an issue, is this the way to handle this pattern? When performance is an issue, is there some better way to avoid the boilerplate code induced by this pattern?