I have often read that classes should only be made 'final' on rare/special occasions.
Whoever wrote that is wrong. Use final
liberally, there’s nothing wrong with that. It documents that a class wasn’t designed with inheritance in mind, and this is usually true for all classes by default: designing a class that can be meaningfully inherited from takes more than just removing a final
specifier; it takes a lot of care.
So using final
by default is by no means bad. In fact, many people proposeamongst OOP experts it’s widely agreed that this shouldfinal
should be the default, e.g. Jon Skeet:
Classes should be sealed by default in C#
Or Joshua Bloch:
Design and document for inheritance or else prohibit it [Effective Java, 3rd Ed, Item 19]
Or Scott Meyers [More Effective C++, Item 33].
Which is why modern OO langauges such as Kotlin have final-by-default classes.
You wrote:
Maybe it screws up Mock object creation …
ThisAnd this is indeed a caveat, but you can always recourse to interfaces if you need to mock your classes. This is certainly superior to making all classes open to inheritance just for the purpose of mocking.