Skip to content
The Chat Archive
o3-2025-04-16· OpenAI LMArena Human Preference 140K

So when should i use inheritance? Give me a real example.

  1. User

    So when should i use inheritance? Give me a real example.

  2. Assistant

    🏆 When inheritance really shines

    Composition is usually the first choice, but inheritance is still the right tool when you have all of the following:

    1. A clear and stable “is-a” relationship that is unlikely to change (a Car is a Vehicle, a JwtHandler is an AuthenticationHandler, etc.).
    2. You want to reuse non-trivial code that lives in the base class (not just an interface contract).
    3. The framework you’re integrating with expects a subtype of a specific base class (ASP.NET Core has many of these extension points).
    4. You only need to vary a small part of the algorithm while keeping the rest intact (Template-Method pattern).

    If those boxes are ticked, inheritance makes your life easier and your code smaller.


    Real ASP.NET Core example: A custom AuthorizationHandler

    ASP.NET Core’s authorization system is explicitly built around inheritance: every requirement handler must derive from AuthorizationHandler<TRequirement>.
    Here composition alone won’t help—you have to inherit to hook into the framework.

    1. Define your requirement

    public class MinimumAgeRequirement : IAuthorizationRequirement
    {
        public int MinimumAge { get; }
        public MinimumAgeRequirement(int minimumAge) => MinimumAge = minimumAge;
    }
    

    2. Inherit from AuthorizationHandler<TRequirement>

    public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
    {
        protected override Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            MinimumAgeRequirement requirement)
        {
            // (1) Get the user's date of birth from a claim
            var dobClaim = context.User.FindFirst("dob");
            if (dobClaim == null) return Task.CompletedTask;
    
            var dateOfBirth = DateTime.Parse(dobClaim.Value);
            var age = DateTime.Today.Year - dateOfBirth.Year;
    
            // (2) If the user is old enough, mark requirement as succeeded
            if (age >= requirement.MinimumAge)
                context.Succeed(requirement);
    
            return Task.CompletedTask;
        }
    }
    

    AuthorizationHandler<TRequirement> already knows how to:

    • register itself in the pipeline,
    • loop through multiple requirements,
    • expose context.Succeed/Fail.

    You only override one method (HandleRequirementAsync) to inject your custom rule—the archetypal Template-Method use-case.

    3. Register and use

    builder.Services.AddAuthorization(opts =>
    {
        opts.AddPolicy("AtLeast21", policy =>
            policy.Requirements.Add(new MinimumAgeRequirement(21)));
    });
    
    builder.Services.AddSingleton<IAuthorizationHandler, MinimumAgeHandler>();
    

    Now any controller or Razor page can do:

    [Authorize(Policy = "AtLeast21")]
    public IActionResult OrderBeer() => Ok("🍺 Cheers!");
    

    Without inheritance you’d have to rewrite all the surrounding glue code that the base class already gives you for free.


    Other day-to-day inheritance spots in ASP.NET Core

    ScenarioBase class you inheritWhy inheritance is the correct hook
    Custom authentication schemeAuthenticationHandler<TOptions>Supplies challenge/forbid plumbing
    Custom exception handling filterExceptionFilterAttributeFramework discovers it via attribute inheritance
    Custom model binderModelBinderAttribute + IModelBinderThe attribute must derive from a base attribute
    Custom Tag HelperTagHelperBase class gives you HTML generation helpers
    Unit-of-work controller baseControllerBaseShare common logic across multiple controllers

    Quick checklist before you subclass 📝

    1. Does “Subclass is-a BaseClass” make sense in domain language?
    2. Is the base class part of a framework-mandated extension point?
    3. Will overriding one or two methods suffice, and the rest of the algorithm should remain intact?
    4. Are you okay with the tight coupling (e.g., you can’t swap the base class at runtime)?

    If yes ➜ inheritance is probably the right call.
    If no ➜ favour composition (interfaces + DI).


    TL;DR

    Use inheritance when you need to plug into an existing framework hook or share a complex, stable algorithm—like writing a custom AuthorizationHandler in ASP.NET Core. Everywhere else, lean toward composition for flexibility and testability.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.