Reputation: 4730
I have a scraper that scans a webpage for specific pieces of information and creates an object from them. One of the properties is an id that is later used to query for remaining properties of the new object.
Because the responsibility of building this object is separated into several classes (the scraper class and the class that queries using one of the properties), I'd like to avoid using passing around a Builder (also, Builder pattern with an accessor seems weird to me).
At the same time, I would like to avoid null references in the object that is being built.
Guava's Optional doesn't seem like a good fit either as the properties of the object will definitely not be null after all steps of its construction have finished.
I could create separate classes, like this:
class ScrapeablePersonImportPart {
String surname;
Year yearOfBirth;
String externalId;
// ... getters, constructor ...
}
class PersonImport extends ScrapeablePersonImportPart {
SocialSecurityNumber ssn;
Color favoriteColor;
// ... getters, constructor ...
PersonImport( ScrapeablePersonImportPart part, SocialSecurityNumber ssn, Color favoriteColor ) {
this.surname = part.getSurname();
this.yearOfBirth = part.getYearOfBirth();
this.externalId = part.getExternalId();
this.ssn = ssn;
this.favoriteColor = favoriteColor;
}
}
Or I could avoid subclassing and use composition instead.
It is quite likely that the construction could compose of even more steps as the program evolves.
Does the solution with several separate classes look reasonable?
Upvotes: 2
Views: 93
Reputation: 30032
I would use composition instead, since you are passing in a ScrapeablePersonImportPart
you can delegate to it rather than inherit from it. Since you may have a new XYZPart
that gets passed in it makes sense to delegate since you can't inherit from both anyway.
If these are just dummy objects for holding dynamic fields of data, I would be tempted to use a HashMap
.
Upvotes: 1