Reading this article (by Eric Lippert), it has four arguments as to why you should use sealed
, however, I don't understand why we actually need it. Philosophical/aesthetic reasons aside, why do we need to use sealed?
I can see how things like readonly
from C# or const
from C++ actually catch genuine errors. Is there any type of error that sealed
can catch?
An often cited reason for sealing a class is because, it hasn't been to designed to be extended. What does that mean? Why is it important? Are there any real examples of this?
The point on compatibility isn't a reason why we need to seal classes but why it should be default.
The final point again is strange, because sealing your class doesn't prevent someone providing an alternative implementation in a heirachy.
Edit:
If I didn't put enough emphasis, on it already I'm looking for reasons we actually need it. Not the usual, "someone else might write bad code". I understand that plenty of people like using sealed
for design intent, but I'm looking for a practical purpose beyond that.
Best Answer
It means that it is difficult for people to obey the Liskov Substitution Principle (or less likely, the Open Closed Principle) with the class as is. It has subtle, or difficult to enforce behavior that inheritors are likely to screw up. Or they're not likely to screw up, but the impact of screwing them up is huge.
Sure it does. If some method takes object
A
or some other class uses typeA
, by havingA
sealed, people cannot override it withB
and then passB
into the method or use it in the class. Consumers ofA
can see it's sealed and know thatA
is the only behavior they're getting.All that said, we don't need
sealed
- just like we don't needreadonly
. They are tools to help programmers prevent misuse, because misuse leads to bugs. Though personally, I dislikesealed
; even in these days where composition over inheritence is well known, it is rare that you can say "nobody will ever need to extend this" and actually be right.