Facade
A facade is a simple front for a messy subsystem. Callers use one type and a handful of methods. The facade talks to the many classes behind it.
Detailed Explanation
A checkout might need inventory, pricing, tax, payment, and email. Exposing all five services to a controller makes every screen know the graph. A CheckoutFacade.placeOrder(cart) sequences the calls, translates exceptions, and returns a result. The subsystem can stay rich for experts; most callers stay on the facade.
java.net.URL opening a stream is a small facade over sockets and protocol handlers. Files is a facade over NIO channels and file systems. SLF4J is a facade over logging backends.
Facade is not adapter: there is no "foreign interface we must match". You design the simple interface. Facade is not mediator: a mediator lets colleagues talk through a hub; a facade is for clients outside the subsystem.
You reach for a facade when a package has grown a wide API and most clients need a script of calls. You do not put all business rules in the facade until it becomes a god class. Keep it as orchestration: validate input, call services, map errors.
The cost of a facade that hides too much is a leaky abstraction: callers need a flag for every hidden step, and the facade grows parameter lists. Offer an escape hatch (access to the inner services) for the rare case. The cost of no facade is duplicated orchestration in five controllers.
Package-private subsystem types plus a public facade is a good Java shape. JPMS can export only the facade's package.
Write the facade after the third copy of the same five-line sequence, not on day one. A facade invented too early is just another name for a service that nobody needed. When you do write it, keep return types in the language of the caller (an OrderReceipt, not a tuple of five vendor objects). That is the simplification. Renaming placeOrder to executeCheckoutPipeline is not.
Code Examples
class Tax {
int add(int paise) {
return paise + paise * 18 / 100;
}
}
class Ledger {
void record(int paise) {
System.out.println("led " + paise);
}
}
public class CheckoutFacade {
private final Tax tax = new Tax();
private final Ledger ledger = new Ledger();
public int pay(int paise) {
int total = tax.add(paise);
ledger.record(total);
return total;
}
public static void main(String[] args) {
System.out.println(new CheckoutFacade().pay(10000));
// prints:
// led 11800
// 11800
}
}Common Gotchas
A facade that absorbs every new feature becomes a god class
split by use case.
Experts may still need the inner types
do not hide them so hard that they invent a second path.