Facade Pattern: The Clean Face of Complexity
Is your main class becoming a 'God Class'? Learn how the Facade pattern simplifies complex systems by providing a clean, easy-to-use interface for clients.
The word Facade refers to the external face of a building. From the outside, a skyscraper looks clean and simple, but inside, there are thousands of complex systems (wiring, plumbing, elevators) at play.
The Problem: The "God Class"
As your application grows, a class like Flipkart or Amazon might become hundreds of lines long. It has to talk to Inventory, Payment, Shipping, and Notification services all at once.
If the client code (like a Mobile App) has to call 10 different services just to "Place an Order," the client becomes tightly coupled to your messy internal logic.
The Solution: The Boundary Class
Facade suggests refactoring this complexity into dedicated intermediate classes that provide a clean, one-click interface.
- Before Facade:
MobileAppcallsInventory.check(),Payment.pay(),Shipping.book(). - After Facade:
MobileAppcallsOrderFacade.placeOrder(). The Facade handles all the internal mess.
Java Implementation
public class OrderFacade {
private InventoryService inventory;
private PaymentService payment;
private ShippingService shipping;
public void placeOrder(String userId, String productId) {
// All the complex coordination happens here!
if (inventory.isAvailable(productId)) {
payment.process(userId);
shipping.schedule(productId);
}
}
}Java vs. JavaScript Perspective
1. In Java (Enterprise Architecture)
In Java, Facades are often used at the Service Layer. When you see a @Service in Spring Boot that coordinates between multiple @Repository classes, you are looking at a Facade. It protects the Controllers from knowing about database complexities.
2. In JavaScript / TypeScript
In the JS world, Facades are common in API Clients. Instead of making 5 separate fetch() calls in your React component, you create an api.ts file with a checkout() function. This function is your Facade--it hides the complexity of network calls from your UI.
Facade vs. Adapter
It's easy to confuse these two:
- Adapter: Changes the interface (e.g., Square hole to Round peg).
- Facade: Simplifies the interface (e.g., 5 buttons to 1 button).
In our next part, we move to Behavioral Patterns and learn how to swap algorithms dynamically with the Strategy Pattern.
Keep reading