OOP Philosophy (excerpt on composition and inheritance from programming in Scala)

In the Scala Program, p. 239, the first paragraph says:

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

I do not understand. Can someone show an example of such a situation, preferably with some code?

+4
source share
1 answer

The fragile base class problem is common to all systems that support inheritance. This means that changes in your supertype (the class you inherit from) can get unexpected results: the change forces you to violate your assumptions in the base class. See this related SO question for an explanation and examples.

Unlike Scala, exports back additions to parent classes to external, independent properties that you can add to a subtype using Mixin Composition. See this example and consider " RichIterator " as the change that you would like to work on the AbsIterator base once it has been defined. See how mixin doesn't change a parent, but is it still easy to reuse in a subtype?

+7
source

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


All Articles