If you want to be a better .NET programmer, there is one book to read from A to Z: CLR via C# by Jeffrey Richter. At page 171, Jeffrey wrote an opinion on the sealed keyword:
When
defining a new type, compilers should make the class sealed by default so that
the class cannot be used as a base class. Instead, many compilers, including
C#, default to unsealed classes and allow the programmer to explicitly mark a
class as sealed by using the sealed keyword. Obviously, it is too late now, but
I think that today’s compilers have chosen the wrong default and it would be
nice if it could change with future compilers. There are three reasons why a
sealed class is better than an unsealed class:
- Versioning: When a class is originally sealed, it can change to unsealed in the future without breaking compatibility. (…)
- Performance: (…) if the JIT compiler sees a
call to a virtual method using a sealed types, the JIT compiler can
produce more efficient code by calling the method non-virtually.(…)
- Security and Predictability:
A class must protect its own state and not allow itself to ever become
corrupted. When a class is unsealed, a derived class can access and
manipulate the base class’s state if any data fields or methods that
internally manipulate fields are accessible and not private.(…)
Personally, I completely agree with this opinion. The result of the sealed keyword choice instead of unsealed is
that the vast majority of .NET programmers let their classes unsealed
without even considering making them sealed. Thus, there are high
chances that the code base you are currently working on is full of
unsealed classes that should be sealed.
The language CQL and the tool NDepend can come to the rescue. The following CQL query lists all classes that are unsealed but that don’t have any derived class.
SELECT TYPES WHERE IsClass AND NbChildren ==0 AND !IsSealed
You should consider carefully the list
of classes matched by this query because they should likely be sealed. Of
course, if you are writing a framework you can have some public unsealed classes
that don’t have any derived class in the context of your framework code base.
Posted
Sat, Jan 5 2008 7:28 PM
by
Patrick Smacchia