Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return new instance of subclass while initializing parent class?

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?

like image 673
Torbjörn Avatar asked Jun 17 '12 19:06

Torbjörn


1 Answers

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.

like image 145
ComDubh Avatar answered Nov 09 '22 17:11

ComDubh