0

Dart Example.

abstract class Figure{
  final int numberOfCorners;
  
  Figure(this.numberOfCorners);
}

class Square extends Figure{
  Square():super(4);
}

class Triangle extends Figure{
  Triangle():super(3);
}

It confuses me that this is actually a narrowing. Derived classes finally define base class field. It is the opposite of extending (adding new methods\fields). But I see this pattern regularly.

Which architectural pattern would make more sense?

cheiser
  • 126
  • 1
  • 10
  • This depends more on how these types are used, not the types themselves. The answer can only be given in a wider context i.e. "What are the pros and cons of this design for this problem when we use this approach? What are the pros and cons with an alternative approach?" While it's possible that these attributes can be described objectively, the choice of "better"/"makes more sense" will be subjective. – Zdeněk Jelínek Feb 20 '22 at 08:29
  • Feel free to ask any question. If my reply helps then you can upvote or mark it as an answer to simplify the future search of other users. Pelase, see [How does accepting an answer work?](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – StepUp Feb 23 '22 at 15:04

1 Answers1

0

There are many opinions about declaration fields in base class. In my view, it makes very tight coupling between base and derived classes. It creates a fragile and rigid relationship between classes. So I would create these fields in classes and avoid inheritance here. Read more about when your inheritance is all about attributes.

Inheritance can be violated very easily. It works fine, if it is used appropriately.

Let me show an example where inheritance misused. For example, there is a base class called “Duck” and you have method “Fly()” in base class. But not all ducks can fly. But our derived class “NotFlyingDuck” inherits method “Fly()”. And by creating derived classes “NotFlyingDuck”, we violate Liskov substitution principle.

The general rule I met is that inheritance should be used to declare behaviour in base class and all derived classes should implement this behaviour. You can read more here. So if all public methods in derived classes should be taken from base class, then it means that it is possible to use inheritance.

StepUp
  • 36,391
  • 15
  • 88
  • 148