Given a class hierarchy as follows:
class A
def initialize(param)
if param == 1 then
#initialize and return instance of B
else
#initialize and return instance of C
end
end
end
class B < A
end
class C < A
end
Is it possible to actually initialize and return an instance of B
or C
when initializing A
? I.e. my_obj = A.new(param)
would result in my_obj
being an instance of class B
or C
depending on the value of param
, which gets checked in A.initialize(param)
.
In my usecase its only known at runtime which subclass (B
or C
) to use and the parent class (A
) is basically never really used.
I thought it might be a good idea to move the logic of deciding whether B
or C
into their common ancestor.
If this is not possible (or bad style), where should I put the check of param
and the decision which class to initialize?
You're breaking a fundamental OO principle here -- classes should know nothing about their subclasses. Of course, sometimes principles should be broken, but there's no apparent reason to do it here.
A far better solution is to shift the instantiation logic to a factory method in a separate class. The factory method takes the same arguments as the A's initializer above, and returns an instance of the appropriate class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With