Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this bad Object Oriented Design? (derived class used in base class)

Can someone tell me if this class structure is bad?

class abstract Parent{
  public Child Foo(){
    return new Child();
  }
}

class Child : Parent{}

I've heard that referring to a derived type from a base type is always bad and signs of bad design. Can someone tell me why this is bad or even if it is bad?

like image 258
Earlz Avatar asked Jan 23 '23 02:01

Earlz


1 Answers

It looks to me like you are using the base class as a factory. I would recommend against this design because it reduces the cohesion of the base class (it's both base class and factory) and increases coupling in the base class (as it references the derived class(es)).

Create a factory class separate from the base class and these issues go away.

like image 185
dkackman Avatar answered Feb 03 '23 13:02

dkackman