Currently I am constructing a view object from a search result (which comes from a different single resource) like this:
ViewObject vo = searchResultToViewObjectMapper.map(searchResult);
This works fine.
However, now I want to add some pictures. These pictures are url’s and I can only determine their location via some other resource than the search result comes from.
My first thought would be to use the Builder Pattern, it would become:
ViewObject vo = viewObjectBuilder.build(searchResult);
and the viewObjectBuilder would do something like this:
private SomeOtherResourceRepository someOtherResourceRepo;
private SomeUrlBuilder someUrlBuilder;
private SearchResultToViewObjectMapper searchResultToViewObjectMapper;
public ViewObject build(SearchResult) {
ViewObject vo = searchResultToViewObjectMapper.map(searchResult);
String reference = someOtherResourceRepo.getOtherResource(searchResult);
String urlToOtherResource = someUrlBuilder.build(reference);
vo.setUrlToOtherResource(reference);
return vo;
}
The question is: Is this a good way to this? Or are there other (better) ways? I’m also curious how a DDD approach would do this.
Thanks in advance!
Using a factory will work for you if you have all of the resources available before you create your object – just pass them on to the factory method and it will do the magic.
If the object you are creating (the view) is created in steps – i.e. first you only have the
searchResult, after this you dig more and get some extra URLs which are added to the view, and then you do some more searching for more information, and only then you want to get the view object, a builder would be a better solution.