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

πŸ“š Interview question

What is the Facade pattern? Give examples from .NET and from a typical business application, and explain how a good facade differs from a 'god service' that does everything.

Facade intent (a simple entry point over a subsystem), .NET examples (File.ReadAllTextAsync, HttpClient, JsonSerializer, DbContext), an order-checkout facade, facade vs god service vs application service, and keeping facades thin.

Intermediate Theory Intermediate api-design application-services cohesion design-patterns facade

🎯 Key points

  • Facade gives a simple, higher-level interface over a complex subsystem; the subsystem classes still exist and can be used directly
  • .NET examples: File.ReadAllTextAsync hides FileStream, StreamReader and encoding detection; HttpClient hides the handler pipeline; JsonSerializer hides readers, writers and converters; DbContext fronts change tracking and querying
  • In business code, a CheckoutFacade or application service orchestrates inventory, payment and shipping for one use case
  • A good facade is thin orchestration: it delegates, it doesn't own the business rules of the subsystems
  • A god service is a facade that grew: dozens of unrelated methods, its own business logic, many dependencies, low cohesion
  • Signs of a god service: constructor with 10+ dependencies, methods for unrelated use cases, every change touches it, huge test setup
  • Testing: a use-case facade is tested with a few fakes for its subsystems; a god service needs every dependency mocked in every test, which makes tests brittle and slow to write
  • Fix: split by use case or bounded context, push rules into domain objects, keep one facade per client need

⏱ 30-second answer

Facade puts a simple entry point in front of a complex subsystem, so clients make one call instead of coordinating many classes. The subsystem stays available for anyone who needs more control.

.NET examples: File.ReadAllTextAsync (hides FileStream, StreamReader and encoding detection), HttpClient (hides the handler pipeline), JsonSerializer and DbContext. In business code, a checkout facade or application service coordinates inventory, payment and shipping for one use case.

The difference from a god service is cohesion. A facade is thin orchestration for one client need, and it delegates the rules to the subsystems. A god service has dozens of unrelated methods, owns business logic and has a ten-dependency constructor. The trade-off is that facades tend to grow, so split them by use case.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"A facade is a simple front door to a complicated subsystem. Instead of the client knowing how five classes fit together, it calls one method on the facade, which coordinates them. The subsystem doesn't disappear: if you need fine control, you can still use the parts directly. That's what distinguishes a facade from an abstraction that hides things completely.

.NET has lots of them. File.ReadAllTextAsync opens a FileStream, wraps it in a StreamReader, detects the encoding and reads to the end, all behind one call, and you can drop down to the streams yourself when you need to. HttpClient is a facade over the HttpMessageHandler pipeline, JsonSerializer over Utf8JsonReader/Writer and the converters, and DbContext over change tracking, the query pipeline and the database connection. In application code I write facades for use cases. A PlaceOrder application service checks stock, reserves it, takes payment and books shipping, while each of those subsystems keeps its own rules.

The mistake I see is the facade that keeps growing into a god service: an OrderService with forty methods covering checkout, refunds, reporting and admin, a constructor with twelve dependencies, and business rules mixed in because it was the easiest place to put them. Every change touches it and every test needs a huge setup. My fix is to split by use case, with one class or handler per operation, and push the rules back into the domain objects. A facade should be thin orchestration for one client need, not the place the logic lives."


Facade in .NET

Facade Subsystem it hides
File.ReadAllTextAsync / WriteAllTextAsync FileStream, StreamReader/Writer, encoding
HttpClient HttpMessageHandler chain, connection pooling
JsonSerializer Utf8JsonReader/Writer, converters, metadata
DbContext Change tracker, query compiler, connection, transactions
WebApplication Host, server, middleware pipeline, routing

Facade vs god service

Facade God service
Scope One client need or use case Everything related to a noun ("Order")
Logic Orchestration only Business rules, validation, mapping, I/O
Dependencies A few subsystems 10+
Change frequency Changes with the use case Changes with every feature
Tests Small, with fakes for subsystems Large setups, brittle

Production example

An insurance platform's PolicyService had 58 public methods and 14 constructor dependencies, and appeared in 70% of pull requests. Splitting it into eleven use-case handlers (quote, bind, endorse, cancel…) with rules moved into the Policy aggregate cut merge conflicts sharply. The median handler test went from about 120 lines of setup to 25.

πŸ” What the interviewer is checking

Checks understanding of Facade's purpose and the judgement to spot when it degrades into a god object.

Green flags

  • Defines Facade as simplification over a subsystem that stays usable.
  • Gives framework examples and a use-case example.
  • Clearly separates orchestration from business rules.
  • Knows the signs of a god service and how to split it.

Red flags

  • Thinks any wrapper class is a facade.
  • Puts all logic in a big service and calls it a facade.
  • No awareness of cohesion.

πŸ“š Learn in depth

1. Structure

Client ──▢ CheckoutFacade.PlaceOrderAsync(cart)
                 β”‚
     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
     β–Ό           β–Ό                 β–Ό
 Inventory    Payments          Shipping       (subsystems still usable directly)

2. Facade vs other wrappers

Pattern Interface Intent
Facade New, simpler, over many classes Simplify
Adapter Different shape over one class Convert
Decorator Same interface over one object Add behaviour
Proxy Same interface over one object Control access

3. Facade and layers

In layered and clean architectures, an application service (or a command handler) is a facade for one use case over the domain and infrastructure. Controllers call it, so they don't orchestrate repositories, payment clients and email senders themselves. The application service coordinates but delegates decisions to domain objects ("Tell, Don't Ask").

4. How facades become god services

  1. A facade starts with one use case.
  2. A related method is added "because it's the Order service".
  3. Validation and rules are added there because the domain model is anaemic.
  4. Cross-cutting concerns (logging, caching) are added inline.

Measure it: number of public methods, constructor parameters, lines of code, and how often the file changes (git log --format=oneline -- OrderService.cs | wc -l). High churn plus high size is the signal.

5. Refactoring a god service

  • Group methods by use case and by the data they touch (cohesion).
  • Extract one handler or service per use case; start with the most changed.
  • Move rules into entities and value objects.
  • Keep the old class as a thin facade delegating to the new handlers until callers move (strangler approach).

Try it yourself

  1. Write File.ReadAllTextAsync by hand using FileStream and StreamReader to see what the facade hides.
  2. List the public methods of the largest service in your codebase and group them by use case.
  3. Count constructor dependencies across services and look at the top three.
  4. Extract one use case into its own handler and measure test setup lines before and after.

πŸ’» Code

A thin use-case facade that orchestrates and delegates rules to the domain:

namespace Checkout;

public sealed record PlaceOrderResult(Guid OrderId, string PaymentReference, string TrackingNumber);

// Facade for ONE client need: placing an order
public sealed class PlaceOrderHandler(
    IInventory inventory,
    IPaymentGateway payments,
    IShipping shipping,
    IOrderRepository orders)
{
    public async Task<PlaceOrderResult> HandleAsync(Cart cart, CancellationToken ct)
    {
        Order order = Order.CreateFrom(cart);                      // rules live in the domain object

        await inventory.ReserveAsync(order.Lines, ct);             // subsystems do their own work
        PaymentResult payment = await payments.ChargeAsync(order.Id, order.Total, cart.PaymentToken, ct);
        if (!payment.Succeeded)
        {
            await inventory.ReleaseAsync(order.Lines, ct);
            throw new PaymentDeclinedException(payment.DeclineReason);
        }

        order.MarkPaid(payment.Reference!);
        string tracking = await shipping.BookAsync(order, ct);
        await orders.AddAsync(order, ct);

        return new PlaceOrderResult(order.Id, payment.Reference!, tracking);
    }
}

// The god service it replaced (shape only):
// public class OrderService(IInventory, IPaymentGateway, IShipping, IOrderRepository, IEmailSender,
//     IReportBuilder, IRefundService, IAuditLog, ITaxCalculator, IDiscountEngine, IPdfRenderer, ICrm)
// {
//     PlaceOrder, CancelOrder, Refund, ResendInvoice, MonthlyReport, ExportCsv, ApplyDiscount, ... (40+ methods)
// }

⚠ Common mistakes

  • Mistake: Putting business rules in the facade. Why it is wrong: Rules get duplicated across facades and the domain becomes anaemic. Instead: Keep rules in domain objects; the facade orchestrates.
  • Mistake: One facade per noun (OrderService) instead of per use case. Why it is wrong: Unrelated operations pile up and cohesion collapses. Instead: One handler or service per use case or client need.
  • Mistake: Hiding the subsystem completely so nobody can use it directly. Why it is wrong: Advanced callers then add more facade methods instead of using the parts. Instead: Keep subsystem APIs public where sensible; the facade is a convenience.
  • Mistake: Wrapping a single class in a "facade" that only forwards. Why it is wrong: It adds a layer without simplifying anything. Instead: Use the class directly, or use Adapter if the interface needs converting.
  • Mistake: Ignoring partial failures in orchestration. Why it is wrong: Payment fails after stock is reserved, and the stock is never released. Instead: Compensate explicitly, or use a saga for long-running workflows.
  • Mistake: Letting the constructor grow past a handful of dependencies. Why it is wrong: It's the clearest god-service signal and makes tests painful. Instead: Split the class when dependencies grow.

πŸ› Senior insight: trade-offs

Facades are good for client simplicity and bad for design when overused. The senior skill is noticing when the facade is doing more than orchestration, and splitting it before it becomes the class everyone fears to touch.

Option When it fits Cost When not to
Use-case facade / handler Controllers or jobs need one operation over several subsystems One class per use case Single-call operations
Subsystem-wide facade (SDK-style) Library or module consumers want a simple entry point Can grow large Internal app code with few callers
No facade, call subsystems Few steps, one caller Client knows more Many callers duplicating orchestration

I watch constructor dependency counts and change frequency per file; a service in the top 5% for both is a split candidate.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate describes a god service Why: Checks recognising and fixing low cohesion
    How to answer

    Cohesion is how strongly the parts of a module belong together. A highly cohesive class has methods that work on the same data towards one purpose, so a change to that concept happens in one place. Low cohesion shows up as Utils or Manager classes with unrelated methods, fields that only one or two methods use, and classes that change for many different reasons. I improve it by grouping code around domain concepts and features, moving methods to the data they use, and splitting classes whose fields form separate clusters.

  2. When: Candidate proposes splitting the facade per use case Why: Checks applying SRP without creating hundreds of tiny classes
    How to answer

    SRP says a module should have one reason to change, which Robert C. Martin later phrased as "responsible to one actor": one group of people whose requests drive its changes. It is not "a class does one thing" or "one method per class". In .NET I look for classes that change for unrelated reasons, such as an OrderService that holds pricing rules (finance), email templates (marketing) and SQL (DBA), and split along those change drivers. I stop splitting when the pieces would always change together, because that is just scattering one responsibility across files.

↩ Usually asked after

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

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