NDepend

Improve your .NET code quality with NDepend

Ensure that your classes are declared as sealed when possible

Inheritance is one of the pillar of OOP. However, in the real world, most classes are not designed to be properly inheritable.

Properly designing a class to be inheritable is a tricky task. One must anticipate state initialization, state correctness, state mutability and also non-public methods calls from descendants. Anticipating well code re-use is hard and this requires experience. As a consequence there is no chance that a class gets well designed for inheritance by chance.

However, in both C# and VB.NET, a class is by default inheritable. The C# keyword sealed and the VB.NET keyword NotInheritable must be specified explicitly. Since there is no compiler warning most developers don’t bother to seal their classes. Hence most classes are not properly designed for inheritance but are implicitly declared as inheritable.

As if writing high quality code was not complicated enough here we have a language pitfall.

This is why NDepend proposes the default rule Class with no descendant should be sealed if possible. The CQLinq source code of this rule is pretty obvious:

As explained in the rule’s comments, you won’t get warnings per default for public non-sealed classes with no descendants. Indeed, it might be well that the analyzed code base is a framework and that descendants of such classes are not available at the time of analysis. But if the code base analyzed is an application with no public API it is important to comment this clause and get most public classes declared as sealed.

If you are not convinced that most classes should be sealed, there are also non-obvious reasons. Here is a quote from Jeffrey Richter from his essential book CLR via C#:

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.(…)

In the same vein you can also refer to this Eric Lippert 2004 post where he explains why most .NET Framework classes are sealed per default.

My dad being an early programmer in the 70's, I have been fortunate to switch from playing with Lego, to program my own micro-games, when I was still a kid. Since then I never stop programming.

I graduated in Mathematics and Software engineering. After a decade of C++ programming and consultancy, I got interested in the brand new .NET platform in 2002. I had the chance to write the best-seller book (in French) on .NET and C#, published by O'Reilly (> 15.000 copies) and also did manage some academic and professional courses on the platform and C#.

Over the years, I gained a passion for understanding structure and evolution of large complex real-world applications, and for talking with talented developers behind it. As a consequence, I got interested in static code analysis and started the project NDepend.

Today, with more than 8.000 client companies, including many of the Fortune 500 ones, NDepend offers deeper insight and understanding about their code bases to a wide range of professional users around the world.

I live with my wife and our twin babies Léna and Paul, in the beautiful island of Mauritius in the Indian Ocean.

Published by

Patrick Smacchia

My dad being an early programmer in the 70's, I have been fortunate to switch from playing with Lego, to program my own micro-games, when I was still a kid. Since then I never stop programming. I graduated in Mathematics and Software engineering. After a decade of C++ programming and consultancy, I got interested in the brand new .NET platform in 2002. I had the chance to write the best-seller book (in French) on .NET and C#, published by O'Reilly (> 15.000 copies) and also did manage some academic and professional courses on the platform and C#. Over the years, I gained a passion for understanding structure and evolution of large complex real-world applications, and for talking with talented developers behind it. As a consequence, I got interested in static code analysis and started the project NDepend. Today, with more than 8.000 client companies, including many of the Fortune 500 ones, NDepend offers deeper insight and understanding about their code bases to a wide range of professional users around the world. I live with my wife and our twin babies Léna and Paul, in the beautiful island of Mauritius in the Indian Ocean.

Comments:

  1. I wish the sealed keyword was part of the default C# file template in VisualStudio. Changing the default templates on even a single machine is a headache and changing them on all machines across the team is almost unthinkable. Another thing that would be great is an opt-in “sealed by default” mode, similar how the new C# 8.0 nullable reference types operate: You set a flag in your .csproj file saying that classes should be considered sealed by default, and then it would be like that for the entire project.

  2. I strongly disagree. Technology should be enabling, not limiting, and developers should be treated as responsible, not as incompetent. The bad guys will always be able to do what they want, sealed or not.

    Versioning: Obviously that’s the risk of the inheritor. Nothing much changes for implementors, as sealed classes can break compatibility anyway. Both sides should be aware of what they are doing.

    Performance: If you are in situations where such performance difference matters, use structs.

    Security and predictability: The answer is even in the paragraph, use private members, which are the default anyway. When someone marks a member as protected where sealing makes a difference, it’s an intentional indication that this member is supposed to be accessed by inheritors.

    The penalty of doing what you need with sealed classes (e.g. reflection or type providing) is asymmetrically much worse than the penalty for ensuring your unsealed classes behave the way you want.

    Never in my development experience has meeting a sealed type been pleasure. I haven’t ever heard anyone go like ‘oh cool, it’s sealed’ but you can often go ‘oh cool, I can focus on my work rather than reimplementing the whole thing’.

    I am not saying that everything that can be done should be done, but I think the team made a good balanced decision with unsealed but private members by default.

  3. If you don’t know how to program then sealed is locking you down by design. If you choose to mark protected vs public vs private it is your choice, same goes for sealed. Agree this is article is a wash due in part you are stifling creativity.

  4. Interesting. I’ve found over the years that most of my classes that are “derived” from a base class actually need a much more restricted interface to the base class. As a result I don’t inherit that much but make an instance of the “base” class a private instance variable and then use it internally. What I’m concerned about is someone, including myself, later forgetting the actual interface to the class and using one of the base class methods, bypassing the business logic in my class.

  5. I was going to call you an idiot, and then I decided that might be a bit harsh.

    And then I reconsidered. You’re an idiot.

Leave a Reply

Your email address will not be published. Required fields are marked *