4

In Programming in Scala, page 239, the first paragraph says:

Composition and inheritance are two ways to define a new class in terms of another existing class. If what you’re after is primarily code reuse, you should in general prefer composition to inheritance. Only inheritance suffers from the fragile base class problem, in which you can inadvertently break subclasses by changing a superclass.

To me it is unclear. Can anyone show an example of such a situation, preferably with some code?

alain.janinm
  • 19,951
  • 10
  • 65
  • 112
noncom
  • 4,962
  • 3
  • 42
  • 70
  • 1
    In case you want to look at it from the very beginning: https://www.youtube.com/watch?v=6w2Pz3XodH0 - relationship between the philosophy and programming OOP. no scala specifically though. (educational) – ses Feb 22 '22 at 00:49

1 Answers1

7

The fragile base class problem is general to all systems that support inheritance. It means that changes to your supertype (the class you are inheriting from) can get you unexpected results : change makes you break your assumptions on your base class. See this related SO question for explanation & examples.

By contrast Scala exports posterior additions to parent classes to exterior, independent traits, that you can add to a subtype using Mixin Composition. See this example, and consider "RichIterator" as change that you would like to effect on the base AbsIterator, once it has been defined. See how the mixin doesn't change anything of the parent, yet is still easily reusable in a subtype ?

Community
  • 1
  • 1
Francois G
  • 11,957
  • 54
  • 59