I was told “model an abstract container for database objects that constructs accepting a varargs of children and then exposes some children inspection functionality without code repetition”.
This hints to things like “count # of children”, “find by identifier”, etc.
For simplicity’s sake, the code below just has one field from the base abstract DatabaseObject type (i.e. name) but the real code has things like “identifier” and some complex metadata look-up gimmicks.
The idea of this is certainly useful but just looking at what I started to code makes me wanna puke: it’s gonna be a Frankenstein of entanglement if I continue along this path. Any way to make this into decent Java? Any design pattern to reference? (Composite comes to mind…)
Premise: the actual functionality to be shared is useful and indeed applicable to any potential nestable types (Schemas have Tables, Tables have Columns, CompositeIndex(es) have sub-Indexes, etc.), especially the identifier look-ups…
… but “there must be a better way”. I feel that voice inside me saying “whenever you write code like that, slap yourself in the face”.
Help 🙂
public abstract class DatabaseContainerObject<ChildType extends DatabaseObject>
extends DatabaseObject {
protected List<ChildType> children;
public DatabaseContainerObject(String name, ChildType... children) {
super(name);
this.children = new ArrayList<ChildType>(children.length);
this.children.addAll(Arrays.asList(children));
}
protected List<ChildType> getChildren() {
return Collections.unmodifiableList(children);
}
... count ...
... find ...
... sort ...
... remove ...
...
}
Composite comes to mind very fast, but you should also investigate the Decorator Pattern.
Find clearly goes recursive, but Count e.g. is very limited on leaf objects and much the same on all kind of nodes.