Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sealing a class

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?

like image 868
CSharpened Avatar asked Dec 08 '11 16:12

CSharpened


People also ask

What does it mean for a class to be sealed?

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.

How do you seal a class in Java?

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.

When would you use a 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.


2 Answers

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.

like image 154
vc 74 Avatar answered Sep 17 '22 12:09

vc 74


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.

like image 36
CodesInChaos Avatar answered Sep 21 '22 12:09

CodesInChaos