- Published on
Learning Design Patterns: Facade Pattern - Why Always Me?
- Authors
- Name
- Dan Tech
- @dan_0xff
Facade Pattern offers a recommendation for Devs when writing software that wants to integrate multiple Modules and Features together. Instead of direct referencing, reference through a Facade to help simplify dependencies.
The Problem With Working Cross Feature Modules
In project development, it's definitely not the case that you only code alone, or only code with people you are close to. Sometimes you code with a friend in a different time zone, a completely different culture.
Suppose that Dev friend is working on the Login Feature, and you are working on the Home Screen Layout Feature. And the software specification is "User is not logged in, can still view the Home Screen, but when clicking on any Button, the Login screen will appear, after successful Login they will be returned to the previous Home screen."
You have finished building the Home screen, now to handle the case where the user is not logged in, you need to know at least 2 things
- User Login status: This data is in SessionRepository
- Show Login Screen function: This Function is located somewhere in AuthNavigator
What to do now? Is the solution to import SessionRepository and AuthNavigator into the Home Screen? A bit complicated, right? So let the Facade Pattern solve this story for you !!!
Solving Cross Feature Dependencies With Facade Pattern
Instead of exposing SessionRepository and AuthNavigator to the outside, we create AuthFacade to provide only the most necessary and simple Interface for external access + usage.
inteface AuthFacade {
fun isAuth(): Boolean
fun openLogin(): Unit
}
In the logic of the Home Screen, you only need to refer to AuthFacade to perform the necessary operations based on your own Business.
class HomeScreen : Screen {
private val authFacade: AuthFacade by lazy { get() } // sampel code to get authFacade instance from provider
fun handleInterceptClick() {
if(authFacade.isAuth()) {
return false
} else {
authFacade.openLogin()
return true
}
}
}
With this implementation, HomeScreen only references a single Facade to execute its control commands on the Login Feature. This approach makes the source code easier to understand and more concise than directly referencing the Classes / Interfaces of the branch Feature / Module.
Benefits of using Facade Pattern
- Simplification: The Facade Pattern provides a simple, easy-to-use Interface for other modules.
- Increased encapsulation in design: Hides the complexity of the Module, aiming for communication and separation.
The Facade Pattern is essentially a tool that helps you manage complexity when working between different modules or features. By creating an intermediary entity, you can reduce dependencies, simplify, and make the code more readable. Use it when you can!
@dantech wish you success!