📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Template Method pattern? Explain it using BackgroundService.ExecuteAsync and other framework base classes, the difference between abstract steps and virtual hooks, why a base class with protected virtual methods can become fragile, and when you would use composition instead.

Template Method intent and structure, non-virtual skeleton with abstract steps and virtual hooks (NVI idiom), framework examples (BackgroundService.ExecuteAsync and its .NET 10 behaviour change, AuthenticationHandler<T>, Collection<T>, DbContext.OnModelCreating, JsonConverter<T>), the fragile base class problem, virtual calls in constructors, and replacing inheritance with strategies or delegates.

Intermediate Theory Intermediate background-service composition design-patterns inheritance template-method

🎯 Key points

  • Template Method: a base class fixes the algorithm's skeleton in a non-virtual method and lets subclasses fill in steps
  • Abstract steps must be implemented; virtual hooks have a default and are optional; keep the skeleton non-virtual (non-virtual interface idiom)
  • BackgroundService: StartAsync/StopAsync are the skeleton, you override ExecuteAsync; since .NET 10 all of ExecuteAsync runs on a background thread
  • Other framework examples: AuthenticationHandler<TOptions>.HandleAuthenticateAsync, Collection<T>.InsertItem/RemoveItem, DbContext.OnModelCreating, JsonConverter<T>.Read/Write
  • Fragile base class: subclasses depend on when and in what order the base calls their overrides, so base-class changes silently break them
  • Never call virtual members from a constructor: the override runs before the derived constructor has initialised its fields
  • Composition alternative: inject the steps as strategies or delegates into a sealed class; easier to test and combine
  • Use Template Method for a small, stable skeleton owned by a framework; prefer composition in application code

⏱ 30-second answer

Template Method puts an algorithm's skeleton in a base-class method that isn't overridable, and lets subclasses supply the steps: abstract steps they must implement and virtual hooks with defaults they may override.

.NET is full of it: BackgroundService implements StartAsync/StopAsync and you override ExecuteAsync (since .NET 10, all of it runs on a background thread). Also AuthenticationHandler<TOptions>.HandleAuthenticateAsync, Collection<T>.InsertItem, DbContext.OnModelCreating.

The risk is the fragile base class: subclasses depend on when and in what order the base calls them, so changing the base can break them silently.

In application code I often prefer composition: a sealed class that receives its steps as strategies or delegates. The trade-off is inheritance's convenience against tight coupling to the base.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Template Method is the inheritance way of saying 'the steps are always the same, only some of them vary'. A base class has a method that defines the sequence, say read the file, parse each line, validate, save, and that method isn't virtual, so nobody can change the order. The steps that vary are protected: abstract ones every subclass must write, like TryParse, and virtual hooks with a sensible default, like Validate returning true. Each subclass, CustomerCsvImporter, ProductCsvImporter, only fills in its own steps.

The framework examples are the ones I actually use. BackgroundService implements StartAsync and StopAsync, including the cancellation plumbing, and I override ExecuteAsync with my loop. That's Template Method plus a hook. It's worth knowing that .NET 10 changed it: all of ExecuteAsync now runs on a background thread, whereas before the synchronous part before the first await ran during startup and could block other hosted services. AuthenticationHandler<TOptions> is another: the base handles the scheme plumbing and I implement HandleAuthenticateAsync. Collection<T> exposes InsertItem and RemoveItem hooks, and DbContext.OnModelCreating is a hook the base calls when it builds the model.

The mistake I see is building deep hierarchies of these in application code. The subclass ends up depending on details nobody wrote down: the base calls Validate before Save, or calls a hook from its constructor, and the first time someone reorders the base, every importer breaks. That's the fragile base class problem. When the steps vary independently, I'd rather have a sealed Importer<T> that takes an IRecordParser<T> and an IRecordSink<T>, which is easier to test and to combine. Template Method is fine when the framework owns a small, stable skeleton; in my own code I reach for composition first."


Structure

Element Visibility Example
Template method (skeleton) public, non-virtual ImportAsync, BackgroundService.StartAsync
Required step protected abstract TryParse, ExecuteAsync
Optional hook protected virtual with default Validate, DbContext.OnModelCreating

Framework examples

Base class Skeleton You override
BackgroundService StartAsync, StopAsync, cancellation ExecuteAsync
AuthenticationHandler<TOptions> AuthenticateAsync, result caching, events HandleAuthenticateAsync, HandleChallengeAsync
Collection<T> Add, Insert, Remove, Clear InsertItem, RemoveItem, SetItem, ClearItems
DbContext Model building, configuration OnModelCreating, OnConfiguring
JsonConverter<T> Serializer integration Read, Write

Template Method vs composition

Template Method Composition (strategies/delegates)
Binding Compile time, by subclassing Run time, by injection
Combining variations One subclass per combination Mix and match steps
Testing a step Through the subclass The step alone
Coupling Subclass depends on base internals Steps depend on an interface

Production example

A data team had an ImporterBase with six virtual hooks and eleven subclasses. Adding a deduplication step to the base changed the hook order, and three importers began saving unvalidated rows, about 2,000 bad records in a night. Replacing the hierarchy with a sealed Importer<T> composed of a parser, validators and a sink removed the ordering contract, and each importer became a 20-line registration.

πŸ” What the interviewer is checking

Checks that the candidate understands Template Method's inversion of control, recognises it in .NET base classes, and knows the risks of inheritance.

Green flags

  • Explains a non-virtual skeleton with abstract steps and virtual hooks.
  • Uses BackgroundService correctly, ideally knowing the .NET 10 change and exception behaviour.
  • Explains the fragile base class problem and the constructor virtual-call trap.
  • Proposes composition as the alternative with clear criteria.

Red flags

  • Thinks Template Method means any abstract class.
  • Builds deep inheritance trees for reuse.
  • Unaware that exceptions in ExecuteAsync stop the host.

πŸ“š Learn in depth

1. Structure

Β«abstractΒ» FileImporter<T>
  + ImportAsync()            ← template method (non-virtual)
      read β†’ TryParse β†’ Validate β†’ SaveAsync
  # TryParse(line)           ← abstract step
  # Validate(record)         ← virtual hook (default: true)
  # SaveAsync(records)       ← abstract step
        β–²                 β–²
CustomerCsvImporter   ProductCsvImporter

The base calls the subclass ("don't call us, we'll call you", the Hollywood principle). That inversion is what makes it a framework-friendly pattern.

2. The non-virtual interface idiom

Keep public methods non-virtual and expose protected virtual or protected abstract extension points. The base can then add logging, validation or exception handling around the steps without subclasses being able to skip it. Stream follows a version of this: CopyToAsync and the span-based overloads have default implementations built on the core Read/Write methods subclasses override.

3. BackgroundService in detail

  • StartAsync creates a linked cancellation source and starts ExecuteAsync; StopAsync signals cancellation and waits for ExecuteAsync to finish or the host's shutdown timeout.
  • .NET 10 change: all of ExecuteAsync now runs on a background thread. Before .NET 10, the synchronous code before the first await ran on the startup path and blocked other hosted services from starting. If you need work to happen during startup, override StartAsync and do it before calling base.StartAsync, or implement IHostedLifecycleService.
  • Since .NET 6, an unhandled exception in ExecuteAsync stops the host by default (BackgroundServiceExceptionBehavior.StopHost). Catch and log per iteration if the loop should survive failures.

4. The fragile base class problem

A subclass written against a base class depends on implicit contracts: which hooks are called, in what order, how often, and with what state already set. If the base changes any of those, subclasses can break without a compile error. Classic examples:

  • A base AddRange that starts calling Add per item, so a subclass that counts in Add now double counts.
  • A hook moved before a step it relied on.
  • A virtual call in the base constructor: the override runs before the derived class's constructor body and field initialisers that depend on constructor parameters, so it sees uninitialised fields. CA2214 flags this.

Mitigations: seal classes by default, keep hooks few and documented, and don't call virtuals from constructors.

5. Composition alternative

Turn each varying step into a dependency:

Importer<T>(IRecordParser<T> parser, IEnumerable<IValidator<T>> validators, IRecordSink<T> sink)

The skeleton lives in one sealed class; steps are Strategy objects or delegates. You can now combine any parser with any sink, test each step alone, and register variations in DI. The cost is more types and wiring.

6. Costs

Virtual calls per step (negligible), and coupling: each subclass is welded to one base class, and C# allows only one.

Try it yourself

  1. Implement FileImporter<T> with two subclasses and test both through ImportAsync.
  2. Add a virtual call in the base constructor and observe the override seeing a null field; enable CA2214.
  3. Write a BackgroundService with a blocking Thread.Sleep before its first await and compare startup time on .NET 8 and .NET 10.
  4. Rewrite the importer with composition and count the classes needed to support three file formats Γ— two sinks.
  5. Subclass Collection<T> and override InsertItem to reject duplicates.

πŸ’» Code

A Template Method importer, a BackgroundService, and the composition alternative.

namespace Imports;

using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

public sealed record ImportResult(int Read, int Saved);

public abstract class FileImporter<TRecord>
{
    // The template method: public and NOT virtual, so the sequence can't be changed
    public async Task<ImportResult> ImportAsync(Stream input, CancellationToken ct)
    {
        var parsed = new List<TRecord>();
        await foreach (var line in ReadLinesAsync(input, ct))
            if (TryParse(line, out var record)) parsed.Add(record);

        var valid = parsed.Where(Validate).ToList();
        await SaveAsync(valid, ct);
        return new ImportResult(parsed.Count, valid.Count);
    }

    protected abstract bool TryParse(string line, [MaybeNullWhen(false)] out TRecord record);   // required step
    protected virtual bool Validate(TRecord record) => true;                                     // optional hook
    protected abstract Task SaveAsync(IReadOnlyList<TRecord> records, CancellationToken ct);    // required step

    private static async IAsyncEnumerable<string> ReadLinesAsync(Stream input, [EnumeratorCancellation] CancellationToken ct)
    {
        using var reader = new StreamReader(input, leaveOpen: true);
        while (await reader.ReadLineAsync(ct) is { } line)
            yield return line;
    }
}

public sealed record Customer(string Email, string Name);

public sealed class CustomerCsvImporter(CustomersDbContext db) : FileImporter<Customer>
{
    protected override bool TryParse(string line, [MaybeNullWhen(false)] out Customer record)
    {
        var parts = line.Split(',');
        record = parts.Length == 2 ? new Customer(parts[0].Trim(), parts[1].Trim()) : null;
        return record is not null;
    }

    protected override bool Validate(Customer c) => c.Email.Contains('@');

    protected override async Task SaveAsync(IReadOnlyList<Customer> records, CancellationToken ct)
    {
        db.Customers.AddRange(records);
        await db.SaveChangesAsync(ct);
    }
}
namespace Imports;

// Framework Template Method: BackgroundService owns StartAsync/StopAsync; we fill in ExecuteAsync.
// On .NET 10 the whole method runs on a background thread, so it never blocks other services starting.
public sealed class CleanupWorker(IServiceScopeFactory scopes, ILogger<CleanupWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
        while (await timer.WaitForNextTickAsync(stoppingToken))
        {
            try
            {
                await using var scope = scopes.CreateAsyncScope();
                var db = scope.ServiceProvider.GetRequiredService<CustomersDbContext>();
                var removed = await db.Customers.Where(c => c.Email == "").ExecuteDeleteAsync(stoppingToken);
                logger.LogInformation("Removed {Count} invalid customers", removed);
            }
            catch (Exception ex) when (ex is not OperationCanceledException)
            {
                logger.LogError(ex, "Cleanup failed; retrying next tick");   // unhandled would stop the host
            }
        }
    }
}
namespace Imports;

// Composition alternative: the skeleton is a sealed class; steps are injected strategies
public interface IRecordParser<T> { bool TryParse(string line, [MaybeNullWhen(false)] out T record); }
public interface IRecordSink<T> { Task SaveAsync(IReadOnlyList<T> records, CancellationToken ct); }
public interface IValidator<in T> { bool IsValid(T record); }

public sealed class Importer<T>(IRecordParser<T> parser, IEnumerable<IValidator<T>> validators, IRecordSink<T> sink)
{
    public async Task<ImportResult> ImportAsync(Stream input, CancellationToken ct)
    {
        using var reader = new StreamReader(input, leaveOpen: true);
        var parsed = new List<T>();
        while (await reader.ReadLineAsync(ct) is { } line)
            if (parser.TryParse(line, out var r)) parsed.Add(r);

        var valid = parsed.Where(r => validators.All(v => v.IsValid(r))).ToList();
        await sink.SaveAsync(valid, ct);
        return new ImportResult(parsed.Count, valid.Count);
    }
}

// builder.Services.AddScoped<IRecordParser<Customer>, CustomerCsvParser>();
// builder.Services.AddScoped<IValidator<Customer>, EmailValidator>();
// builder.Services.AddScoped<IRecordSink<Customer>, EfCustomerSink>();
// builder.Services.AddScoped<Importer<Customer>>();

⚠ Common mistakes

  • Mistake: Making the template method itself virtual. Why it is wrong: Subclasses can reorder or skip steps, which defeats the pattern. Instead: Keep the skeleton non-virtual and expose only protected steps and hooks.
  • Mistake: Calling a virtual method from the base class constructor. Why it is wrong: The override runs before the derived constructor has set its fields, so it sees nulls or defaults. Instead: Call hooks from the template method, not the constructor; enable CA2214.
  • Mistake: Doing long synchronous work at the top of ExecuteAsync on .NET 8/9. Why it is wrong: Before .NET 10 it ran on the startup path and delayed other hosted services. Instead: On .NET 10 it's on a background thread; for code that must run during startup, override StartAsync.
  • Mistake: Letting exceptions escape the ExecuteAsync loop. Why it is wrong: By default the host stops when a background service throws. Instead: Catch, log and continue per iteration, or let it stop deliberately.
  • Mistake: Many virtual hooks "for flexibility". Why it is wrong: Every hook is a contract about order and state that subclasses will depend on. Instead: Expose the minimum, seal classes by default, and document when each hook runs.
  • Mistake: Deep hierarchies of template classes in application code. Why it is wrong: Changes to a base ripple through every subclass (fragile base class). Instead: Compose a sealed class from injected steps.
  • Mistake: Creating a base class for two classes that share three lines. Why it is wrong: Inheritance coupling for trivial reuse. Instead: A shared private helper or a small extracted class.

πŸ› Senior insight: trade-offs

Template Method is a framework author's tool: the framework owns the lifecycle and you plug into well-documented hooks. In application code the same need is usually better met with composition, because application "skeletons" change often and the fragile base class problem bites exactly when you change them.

Option When it fits Cost When not to
Framework base class (BackgroundService, AuthenticationHandler<T>) The framework expects it Learn the lifecycle and hooks Never avoid it out of principle
Own abstract base with few hooks Small, stable skeleton, one axis of variation Subclass per variant; fragile if it grows Several independent axes of variation
Composition with strategies Steps vary independently or need testing alone More types and DI wiring Two variants that will never grow
Delegates for steps One or two small steps Less discoverable than named types Steps with dependencies

A useful smell test: if a subclass needs to call base.Method() at exactly the right point to work, the hierarchy is carrying a contract that composition would make explicit.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate explains the base class calling abstract methods Why: Checks Template Method from the OOP and abstract-class perspective
    How to answer

    An abstract class is a base class that cannot be instantiated and may declare abstract members with no body, which every non-abstract derived class must override. Unlike an interface it can hold instance fields, constructors and fully implemented members, so it is the place for shared state and a shared algorithm. The classic use is the template method pattern: a public non-virtual method defines the steps and calls protected abstract or protected virtual hooks. Constructors should be protected. A class can derive from only one abstract class. Adding a new virtual member with a body is non-breaking, but adding a new abstract member breaks every derived class.

  2. When: Candidate suggests replacing the base class with composition Why: Checks the composition vs inheritance decision in depth
    How to answer

    Default to composition: build behaviour from small objects behind interfaces and inject them. It keeps coupling low, lets behaviour change at run time and is easy to test. Use inheritance only when all of these hold: there is a true is-a relationship where every subtype can substitute for the base (Liskov), the base was designed for extension (documented virtual hooks, protected constructor), there is one axis of variation, and you want to share state plus a fixed algorithm (template method). Framework extension points such as BackgroundService, DelegatingHandler and DbContext are good inheritance cases. When a hierarchy explodes or subclasses override things to throw NotSupportedException, refactor by extracting the varying behaviour into strategies and composing them.

  3. When: Candidate mentions BackgroundService.ExecuteAsync Why: Checks safe background work patterns in ASP.NET Core
    How to answer

    Fire-and-forget means starting a task and not awaiting it, such as _ = SendEmailAsync(). The risks are: exceptions are never observed, scoped services like DbContext are disposed when the request ends (giving ObjectDisposedException), work is lost on shutdown or crash, there is no limit on how much work piles up, and HttpContext may be used after the request is gone. In ASP.NET Core, hand the work to a queue (Channel<T>) processed by a BackgroundService that creates its own scope, logs failures and drains on shutdown. If the work must not be lost, use a durable queue or an outbox table.

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me