1

Why is the HttpContext an abstract class and not an interface?

The class is public abstract, and all the methods are public abstract. I don't understand why this class is an abstract class.

What reasons are there that it is an abstract class instead of an interface?

Fred
  • 12,086
  • 7
  • 60
  • 83
  • 2
    These kinds of design questions are difficult to answer without a canonical source, so it's largely an opinion unless someone from the ASP.NET team is able to come in and answer. That said, I suspect it's because you cannot add members to an interface without breaking the interface contract for developers (add a new member to the interface and everything stops compiling). With an abstract class, `virtual` members can be added that can optionally be implemented. The ASP.NET team has adopted this pattern in several places. – vcsjones Oct 10 '16 at 16:44
  • 1
    Usually abstract base classes contain some default (i.e. utility) or partial implementation that subclass implementations can leverage, whereas with an interface, there's no place to "hang" that stuff. This way, it's easier to "spin up" a customized implementation. Even if all methods are virtual, the door is still open for this to happen, so can it build up "layers" of partial/helper implementation for subclasses. – escape-llc Oct 10 '16 at 17:03
  • @escape-llc Indeed. But in this case that's not the case. Which is what made me wonder... – Fred Oct 10 '16 at 17:05
  • see my revised comment, still applies. – escape-llc Oct 10 '16 at 17:06

2 Answers2

2

This is the reply I got from Daniel Roth at Microsoft who works with ASP.NET Core.

I believe in this case using an abstract class enables adding members in future versions, which you can't do with an interface.

Fred
  • 12,086
  • 7
  • 60
  • 83
0

There are a lot of opinions regarding this topic (here and here for example). And even though the ASP.NET team usually use interfaces, I can think of a few reasons why they chose for an abstract class in this case:

Versioning
I don't expect the HttpContext class to change a lot, but abstract classes version easier than interfaces (they actually don't version at all) since they can be partially implemented using the virtual keyword.

Encapsulation
Abstract classes encapsulate a set of functionalities where interfaces provide more of a contract for a certain functionality. Classes may only implement one abstract class, which makes sense for a HttpContext implementation, such as the DefaultHttpContext.

Backwards compatibility
Although ASP.NET Core is complete rewrite of ASP.NET, developers are used to program against the HttpContext class for years. Both classes share a lot of the characteristics.


Take in mind that I'm just guessing here, perhaps some folks of the ASP.NET team could enlighten us.

Community
  • 1
  • 1
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104