Tuesday, September 11, 2018

Inheritance Allows a Base Class to Share its Clients with Inheritors

Superclassing and subclassing are always there, no matter what language you use.

A lot of people think that superclassing is a good way to share code and avoid redundancy and it might be...but what's the most valuable thing a superclass can share with its subclass?

Many would answer "put a protected method in there so all the child classes can use that!"

That's a way of sharing an algorithm, sure. Yet, is it the most important thing a superclass grants its subclasses?

No. It is not.

The most important thing a superclass can share with its subclasses (and thus all subclasses can share via a common superclass) is its pool of potential clients.

Consider the following two designs...

Two alternative designs, one that promotes reuse of a method through inheritance and one through composition.
Alternative Methods of Reuse

In design (A), we create (or maybe have) a base class and put a protected method in it, which Child1 and Child2 are both able to access. In design (B), we create (or have) a component class, which has an internal (package-private) method on it that is used by two classes (Child1, and Child2).

Both these options facilitate the reuse of the Reused() method. Maybe one of them is better than another for some reason or other but they both solve the reuse problem for the classes that are drawn on the diagram.

Yet, I think there is a kind of sharing that is unique to subclassing. In order to dig into it, I want to examine a different kind of relationship: usage.

Consider the following design...

A class, Client, depends on another class, Server
A Classic UML Depiction of Usage
Almost everyone considers Client to have a relationship with Server. Do you ever think of this as a Server having a relationship with Client? The arrow at the end of the dashed line in UML betrays how we tend to think of this kind of relationship as unidirectional.

Yet, the relationship definitely works both ways.

A depiction of a relationship from a client class to a server class with the client-end emphasized
Even a Usage-Type Dependency is a Two-Way Relationship

Each class has a relationship with all the other classes that couple to it. This relationship is the one thing that can only be shared with some form of subclassing.

Avoiding redundancy in coupling to a class is an enormously powerful property of inheritance and there doesn't appear to be another way to get it. At least, there's not another equivalently-convenient way.

A depiction of several relationships and many potential targets with the question "How many copies would you like?" scrawled in red