Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to prevent class inheritance?

I've been told recently a good practice in object oriented programming that you should always allow inheritance from your classes. I really don't think so, but I have no solid arguments on my mind.

Real-world examples of blocked inheritance:

  1. No C++ STL class (specialized class template) allows inheritance (having non-virtual destructors).
  2. Java has its final class modifier that applies to many standard components, like java.lang.String.

Possible reasons I think are:

  1. Security, since subclass might have access to sensitive internals. (I don't think so -- they won't access private members.)
  2. Performance, since a subclass could mess up our efficient implementations by overriding some of the member functions. (Children won't override non-virtual functions.)
  3. To enforce composition over inheritance. (I fully agree. We shouldn't favor inheritance when it's not needed.)

So my question is: In what circumstances should I intentionally block inheritance?

like image 688
Janusz Lenar Avatar asked May 05 '12 17:05

Janusz Lenar


Video Answer


1 Answers

In fact, the practice that I try to follow, and that Josh Bloch recommends, in his Effective Java book, is exactly the inverse rule of the one you've been told: Unless you have thought about inheritance, designed your class to be inherited, and documented how your class must be inherited, you should always disable inheritance.

I would recommend reading this chapter of Effective Java (you won't regret buying it), and showing it to the person who told you about this rule.

The most obvious reason to disallow inheritance is immutability. An immutable object is simple to use (only one state), can be cached, shared between many objects, and is inherently thread-safe. If the class is inheritable, anyone can extend the class and make it mutable by adding mutable attributes.

like image 184
JB Nizet Avatar answered Sep 18 '22 23:09

JB Nizet