Sealing a class is not something I have taken much notice of in the past however I find myself wondering what is the best practice. If you know a class would not or should not be derived from would you seal it as a matter of precaution of just leave the sealed keyword out knowing that the chances of someone trying to derive from it are slim.
I guess what I am asking is should you seal all classes which are not intended for inheritance just as a matter of good practice?
A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated. The design intent of a sealed class is to indicate that the class is specialized and there is no need to extend it to provide any additional functionality through inheritance to override its behavior.
To seal a class, add the sealed modifier to its declaration. Then, after any extends and implements clauses, add the permits clause. This clause specifies the classes that may extend the sealed class.
Sealed Classes allow us to fix type hierarchies and forbid developers from creating new subclasses. They are useful when we have a very strict inheritance hierarchy, with a specific set of possible subclasses and no others.
If you follow the open/closed principle to the letter, the sealed keyword should never be used. But I guess there are always corner cases.
In application code, where all code that derives from your class is controlled by yourself, I'd leave most classes unsealed by default. If you break code deriving from your class by changing the base class, you can simply fix it.
But sealing is very useful in library code. If you leave a class unsealed, you promise to not break any code that derives from it. i.e. you increase your public surface area. IMO libaries should keep the surface area minimal by default, which implies sealing.
But it's not always necessary to seal the entire class. It can be enough to seal some or all virtual methods. That way code that derives from your class can only extend it, but not modify its current functionality by overriding a method.
Another kind of class that should often be sealed classes with value semantics. It's much harder to implement correct equality and pseudo mutators for unsealed classes. So I'd simply seal them and avoid the additional work unless really necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With