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

πŸ“š Interview question

What is the Bridge pattern, and what problem does it solve? Use a notifications example (message types × channels) and explain how ILogger/ILoggerProvider and HttpClient/HttpMessageHandler are bridges in .NET. How is Bridge different from Adapter and Strategy?

Bridge intent (separate an abstraction from its implementation so both vary independently), avoiding M×N class explosions, notification types × channels in C#, ILogger over ILoggerProvider and HttpClient over HttpMessageHandler, and Bridge vs Adapter vs Strategy.

Mid-Level Theory Intermediate bridge composition design-patterns httpclient logging notifications

🎯 Key points

  • Bridge separates an abstraction from its implementation so the two hierarchies vary independently, joined by composition
  • Without it, M variations × N implementations need M×N subclasses (4 message types × 3 channels = 12); with it, M + N classes
  • Notifications: abstraction = message kinds (OrderShipped, PasswordReset) that build content; implementor = IChannel (email, SMS, push) that delivers it
  • ILogger (what you log, categories, extension methods) bridges to ILoggerProvider implementations (console, OpenTelemetry, Application Insights); LoggerFactory fans one ILogger out to every provider
  • HttpClient (GetAsync, PostAsJsonAsync, timeouts) bridges to HttpMessageHandler (SocketsHttpHandler, test fake handlers, DelegatingHandler chains)
  • Bridge is designed up front to let both sides evolve; Adapter is retrofitted to make an existing interface fit
  • Strategy swaps one algorithm inside a context; Bridge structures two whole hierarchies; the code can look similar, the intent differs
  • Cost: an extra interface and indirection; only worth it when both dimensions genuinely vary

⏱ 30-second answer

Bridge splits an abstraction from its implementation so the two can vary independently, linked by composition. It prevents class explosions: 4 message types Γ— 3 channels would need 12 subclasses, but with a bridge it's 4 message classes plus 3 channel classes.

.NET has two well-known bridges:

  • ILogger β†’ ILoggerProvider: what you log is separate from where it goes (console, OpenTelemetry, Application Insights).
  • HttpClient β†’ HttpMessageHandler: a friendly request API on one side, and the transport (SocketsHttpHandler, or a fake handler in tests) on the other.

An Adapter is retrofitted to make an existing interface fit, whereas a Bridge is designed up front. A Strategy swaps one algorithm. The trade-off is an extra interface that only pays off when both dimensions really change.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Bridge is about two dimensions that change independently. Without it you tend to model them with inheritance and get a class for every combination. Take notifications. We have message types like order shipped, password reset and invoice due, and channels like email, SMS and push. Model that with inheritance and you end up with OrderShippedEmail, OrderShippedSms, PasswordResetEmail and so on: M times N classes. Adding WhatsApp means one new class per message type, and a bug fix in SMS formatting has to be repeated in each of them. With Bridge, the message side, the abstraction, builds the content, and it holds a reference to an IChannel, the implementor, that knows how to deliver it. Now it's M plus N classes, and the two sides grow separately.

The framework's best examples are logging and HTTP. ILogger is the abstraction you code against: categories, levels, LogInformation and the source-generated [LoggerMessage] methods. Where the logs actually go is the implementor side: ILoggerProvider for the console, OpenTelemetry or Application Insights. The LoggerFactory bridges the two, so one log call reaches every provider, and you can add a provider without touching any logging call. HttpClient is the same shape. It offers GetFromJsonAsync, timeouts and headers, and delegates the actual sending to an HttpMessageHandler, which is SocketsHttpHandler in production or a fake handler in tests.

The mistake I see is using Bridge when only one dimension varies. Then it's just an extra interface. Compared with the neighbours: Adapter makes an existing, mismatched interface fit after the fact, and Strategy swaps a single algorithm inside one class. Bridge is a design decision you make up front to stop a class hierarchy multiplying."


The class explosion

Approach 4 message types Γ— 3 channels Add a channel Add a message type
Inheritance per combination 12 classes +4 classes +3 classes
Bridge 4 + 3 = 7 classes +1 class +1 class

Bridges in .NET

Abstraction (what) Implementor (how/where) Joined by
ILogger<T> ILoggerProvider (Console, OpenTelemetry, App Insights) LoggerFactory
HttpClient HttpMessageHandler (SocketsHttpHandler, fakes) Constructor / IHttpClientFactory
DbContext + LINQ Database provider (SQL Server, PostgreSQL, SQLite) UseSqlServer() etc.

Bridge vs neighbours

Pattern Intent When designed
Bridge Let two hierarchies vary independently Up front
Adapter Make an existing interface fit After the fact
Strategy Swap one algorithm in a context Either

Production example

A notification service had grown to 15 classes for 5 message types across 3 channels. Adding WhatsApp would have meant 5 more, and a privacy fix that masked phone numbers in SMS logs had been applied to only 3 of the 5 SMS classes. Refactoring to a bridge (message builders + IChannel) produced 8 classes, the masking fix lived in one place, and WhatsApp was one new channel class.

πŸ” What the interviewer is checking

Checks whether the candidate understands Bridge's real purpose (two independent axes) and can recognise it in the framework rather than reciting a definition.

Green flags

  • Explains the MΓ—N vs M+N argument.
  • Gives a concrete two-axis example.
  • Recognises ILogger/ILoggerProvider and HttpClient/HttpMessageHandler.
  • Distinguishes Bridge from Adapter and Strategy by intent.

Red flags

  • Can't explain why Bridge exists.
  • Confuses it with Adapter.
  • Suggests wrapping ILogger in a custom abstraction.

πŸ“š Learn in depth

1. Structure

      Abstraction  ────── holds ──────▢  Β«interfaceΒ» Implementor
      + Send()                              + Deliver(content)
          β–²                                  β–²         β–²        β–²
 RefinedAbstraction(s)                 EmailChannel SmsChannel PushChannel
 OrderShippedNotification
 PasswordResetNotification

The "bridge" is the reference from abstraction to implementor. Each side has its own hierarchy.

2. How logging is a bridge

  • You inject ILogger<OrderService> (the abstraction, with a category).
  • LoggerFactory holds every registered ILoggerProvider. For a category it creates a Logger that wraps one ILogger per provider.
  • logger.LogInformation(...) checks filters and levels, then calls each provider's logger.
  • Adding OpenTelemetry (builder.Logging.AddOpenTelemetry(...)) adds a provider; no logging call changes.

The abstraction side can also evolve independently: [LoggerMessage] source generation, scopes and structured templates work with every provider.

3. How HttpClient is a bridge

HttpClient derives from HttpMessageInvoker, which holds an HttpMessageHandler. Every convenience method (GetStringAsync, PostAsJsonAsync) ends in SendAsync, which calls the handler. Swap the handler and the same client code sends over sockets, WinHTTP, an in-memory test server (WebApplicationFactory.CreateClient()), or a fake that returns canned responses.

4. When to apply Bridge

  • You can name two independent axes of change (what Γ— how, platform Γ— feature).
  • Both axes have, or will soon have, more than one member.
  • You want to switch implementations at run time (configuration, tests).

If only one axis varies, a plain interface (Strategy) is enough.

5. Bridge, Strategy and DI

In a DI world many bridges are just constructor injection: the abstraction takes the implementor interface. The pattern name matters less than the design decision: don't encode two axes in one inheritance tree.

Try it yourself

  1. Write the notification example both ways and count classes when adding a fourth channel.
  2. Write a fake HttpMessageHandler that returns a fixed JSON body and use it with a typed client in a unit test.
  3. Write a tiny ILoggerProvider that collects log entries in a list, register it alongside the console provider, and assert on entries in a test.
  4. Find an inheritance hierarchy in your codebase with names like XyzSqlExporter, XyzCsvExporter, AbcSqlExporter. Is it two axes in one tree?

πŸ’» Code

Notifications as a bridge: message kinds on one side, channels on the other:

namespace Notifications;

public sealed record Recipient(string Email, string? Mobile, string? PushToken);
public sealed record MessageContent(string Subject, string Body);

// Implementor: HOW a message is delivered
public interface IChannel
{
    Task DeliverAsync(Recipient to, MessageContent content, CancellationToken ct);
}

public sealed class EmailChannel(IEmailSender email) : IChannel
{
    public Task DeliverAsync(Recipient to, MessageContent c, CancellationToken ct) =>
        email.SendAsync(to.Email, c.Subject, c.Body, ct);
}

public sealed class SmsChannel(ISmsSender sms, ILogger<SmsChannel> logger) : IChannel
{
    public async Task DeliverAsync(Recipient to, MessageContent c, CancellationToken ct)
    {
        if (to.Mobile is null) return;
        await sms.SendAsync(to.Mobile, c.Body[..Math.Min(160, c.Body.Length)], ct);
        logger.LogInformation("SMS sent to {Mobile}", Mask(to.Mobile));   // one place for privacy masking
    }
    private static string Mask(string m) => m.Length <= 4 ? "****" : new string('*', m.Length - 3) + m[^3..];
}

// Abstraction: WHAT is said; holds the implementor (the bridge)
public abstract class Notification(IChannel channel)
{
    protected abstract MessageContent Build();
    public Task SendAsync(Recipient to, CancellationToken ct) => channel.DeliverAsync(to, Build(), ct);
}

public sealed class OrderShipped(IChannel channel, string orderNumber, string trackingUrl) : Notification(channel)
{
    protected override MessageContent Build() =>
        new($"Order {orderNumber} has shipped", $"Track it here: {trackingUrl}");
}

public sealed class PasswordReset(IChannel channel, Uri resetLink) : Notification(channel)
{
    protected override MessageContent Build() =>
        new("Reset your password", $"Use this link within 30 minutes: {resetLink}");
}

// Usage: any message over any channel
// await new OrderShipped(smsChannel, "A1001", url).SendAsync(customer, ct);
// await new PasswordReset(emailChannel, link).SendAsync(customer, ct);
// The framework bridge in a test: same HttpClient API, fake implementor
namespace Notifications.Tests;

using System.Net;

public sealed class StubHandler(HttpStatusCode code, string json) : HttpMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct) =>
        Task.FromResult(new HttpResponseMessage(code) { Content = new StringContent(json) });
}

// var client = new HttpClient(new StubHandler(HttpStatusCode.OK, "{\"status\":\"sent\"}")) { BaseAddress = new("https://sms.test") };

⚠ Common mistakes

  • Mistake: Modelling two axes in one inheritance tree (OrderShippedSms, OrderShippedEmail...). Why it is wrong: Classes multiply MΓ—N and fixes must be repeated in every combination. Instead: Split into two hierarchies joined by composition.
  • Mistake: Introducing Bridge when only one axis varies. Why it is wrong: It adds an interface and indirection for nothing. Instead: A single interface (Strategy) or plain code until the second axis appears.
  • Mistake: Leaking implementor details into the abstraction (the message builds SMS-specific 160-character text). Why it is wrong: The two sides are coupled again. Instead: The abstraction produces channel-neutral content; channels adapt it.
  • Mistake: Calling any interface-plus-implementation pair a bridge. Why it is wrong: The pattern is specifically about two independently varying hierarchies. Instead: Use the precise term; often it's just dependency inversion.
  • Mistake: Writing a custom logging abstraction over ILogger "to decouple from Microsoft". Why it is wrong: ILogger is already the abstraction side of a bridge; another layer adds nothing. Instead: Code against ILogger and add providers.
  • Mistake: Mocking HttpClient directly. Why it is wrong: Its methods aren't virtual; tests become awkward. Instead: Use the bridge: a fake HttpMessageHandler.

πŸ› Senior insight: trade-offs

Bridge is the pattern that stops an inheritance tree from multiplying. In modern .NET it's mostly invisible: DI plus an interface on the implementor side gives you a bridge by default. The senior skill is spotting two axes of change hiding in one hierarchy and splitting them before the combinations explode.

Option When it fits Cost When not to
Single class with switch One axis, few cases None Cases keep growing
Strategy (one interface) One axis varies One interface Two axes vary
Bridge (two hierarchies) Two independent axes Two hierarchies to understand Only one axis really varies
Framework bridge (ILogger, HttpMessageHandler) Logging, HTTP None Don't wrap it again

A quick test: if adding one item on either axis forces you to create several classes, you have a missing bridge.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate explains the class explosion from inheritance Why: Checks composition versus inheritance, the core of Bridge
    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.

  2. When: Candidate uses an abstract class for notifications and an interface for channels Why: Checks interface versus abstract class for the abstraction and implementor sides
    How to answer

    Choose an interface when you are defining a capability or contract that unrelated types may implement, when a type may need several such contracts, when structs must implement it, or when you need static abstract members for generic code. Choose an abstract class when implementers share state, constructor logic or a fixed algorithm, and when the type is an extension point that will grow, because you can add virtual members with bodies safely. Default interface methods narrowed the gap but cannot hold state, so they are mainly for evolving published interfaces. In libraries, a common pattern is both: consumers depend on the interface, and implementers can derive from an abstract base that does the plumbing.

πŸ›  Real-world problems: how you handle them

Privacy fix missed two of five SMS notification classes
Situation
A notification service on .NET [10] for [a telco's customer portal], sending [~1 million] messages a day across email, SMS and push, with one class per message type per channel (15 classes).
Signals
A privacy review found full mobile numbers in Application Insights logs for some SMS messages, after a fix that was supposed to mask them; [two] message types still logged unmasked numbers.
Investigation
Searched for the logging statement and found it copied into five SMS classes; the masking fix had been applied to three. The class structure encoded message type × channel in one inheritance tree, so every channel concern was duplicated per message type.
Resolution
Immediate: patched the two remaining classes and purged the affected log entries per the retention policy. Real fix: refactored to a bridge (message builders producing channel-neutral content, and one `IChannel` per channel), so masking lives once in `SmsChannel`.
Prevention
A unit test asserting SMS logs never contain a full number; a log-scrubbing processor in the OpenTelemetry pipeline as a second line of defence; a review guideline to flag class names combining two axes.

How to tell it (STAR)

**S:** At [company] a privacy review found full mobile numbers in our logs, even though we had shipped a masking fix. **T:** I owned the notification service and had to close the leak and stop it happening again. **A:** The logging code was copied into five SMS classes, one per message type, and the fix had reached only three. I patched the other two and arranged the log purge, then refactored the service so message types build content and channels deliver it, with masking in exactly one place. **R:** The service went from [15] classes to [8], the leak was closed for every message type, and adding WhatsApp later took [one] class and [two days].

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

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