OOD issue
I encounter a OOP design problem at my work, I want to
ask your suggestion, so if you have some free time to
spare, please help me out.
Let's say I have three classes, A, AHolder, and B.
class B extends A
class AHolder is a container of A, it have
constructors look something like this:
AHolder(X x, Y y, Z z) {
....
...
Queue.add(X.constructA(y,z));
...
..
}
it also have getter like this:
A getNext() {
....
}
now I want to have holder that also can hold B, B can
be constructed by call X.constructB(Y,Z)....based on
Y, determination can be made weather A or B should be
constructed.
the question is which of the following way is better?
1) modify the AHolder class to support to hold both A
and B, B is-a A after all. Since it's possible to
determine weather A or B should be constructed based
on the input y, the constructor can be modified to
look something like this
AHolder(X x,Y y,Z z) {
....
...
if(shouldConstructA(y)) Queue.add(X.constructA(y,z));
else Queue.add(X.constructB(y,z));
...
...
}
caller of the getNext() would have to type cast the
result to B if they are getting a B, they should know
when they need to do this, only thing is it is not obvious that they can use AHolder to hold B.
2)write a class BHolder that extends AHolder...
so the constructor for BHolder will look like
BHolder(X x, Y y, Z z) {
.... // repeat of the code in AHolder(x,y,z)
.... //
Queue.add(X.constructB(y,z)); // only different code
//more repeat of code....
}
B getNext() {
(B) super.getNext();
}
no type cast is needed by the caller...but the code is
repeatitive...and a default Constructor that does
nothing would have to be added to AHolder because
BHolder(..) have to call some constrcutor in super
class and It can not call the AHolder constructor
because the AHolder Constructor constructs A, not B...This
can be dangious because if someone uses the default
constructor, when they call getNext(), they will get a
null object.
I think the first way is better because it's simpler
and cleaner. If you agree, are there some kind of OOP
Design Pattern that address this issue so I can use it
to convince my team lead?
thanks

