Is this a bad object oriented design? (derived class used in the 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 heard that calling a derived type from a base type is always bad and there are signs of poor design. Can someone tell me why this is bad or even if it is bad?

+4
source share
4 answers

To develop a dkackman answer, your factory will ideally return objects of child types, but declared as a parent type.

 class Factory { public Parent Foo() { return new Child(); } public Parent Bar() { return new OtherChild(); } } 

The basic idea is that your calling code should not care about which child class it receives. This is one concept of the Liskov Substitution Principle.

+4
source

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

Create the factory class separately from the base class, and these problems will disappear.

+5
source

It certainly smells bad at many levels. Just ask yourself what will happen if someone continues the Child; or another subclass of Parent is created (instead of Child).

It is hard to imagine a case that would justify this design (perhaps it exists, you could explain what you are trying to achieve). (Are you familiar with the factory pattern?)

In any case, in order to get reasonable behavior for such a design, I think that you need to accept and accept the connection, even try to ensure its observance by making the child’s class final / sealed (impossible to extend) and considering both classes as all. But then again, this could (almost certainly) be better achieved with another clean design.

+1
source

I can say nothing wrong with your design. To be more specific, I need to know your purpose in doing this. But whatever your goal, you will miss polymorphism. So, think in terms of client code, you post the details of the superclass to get an instance of the subclass. Why are we doing this? At least I do not. Remember the design principle, we always want a very cohesive class. Here you violate this principle by providing a factory method to instantiate a subclass.

rajan

-1
source

Source: https://habr.com/ru/post/1309725/


All Articles