I’ve been reading up on patterns recently and came across the facade pattern once again. I remember reading up on this a couple of years ago but never really understood it till now. I thought that the facade patterns was unnecessary as it will create unnecessary classes and complicate the solution. However, after playing around with it and having a better understanding of software development, I can now understand why a facade pattern can be quite useful.

What is the facade pattern?

The facade pattern is a pattern where multiple dependencies in a class should be abstracted out into its own class in order to reduce the number of dependencies. For example, say you have a class that has multiple dependencies:

public class RobotVacuumService { 
    public RobotVacuumService(
        ILoggerService logger,
        IMotorService motorService,
        IVacuumService vacuumService,
        IMopService mopService,
        ILidarService lidarService,
        IBrushService brushService
    )
    {
        // initializations   
    }
}

With the above code, we can see that there are 5 dependencies injected into the service. While having five services might be considered ok, the more services we add into the RobotVacuumService, the more complicated and messy it will become. It becomes more difficult to unit test as there will be more pieces to mock.

The idea behind the facade pattern is to see if we can abstract away another services to simplify things.

How does it work?

So with the RobotVacuumService example above, we can notice that there are three services that have commonalities in them. IBrushService, IVacuumService, and IMopService all relate to cleaning. If we take what’s required from these services and abstract it away into another service, ICleaningService we will reduce the depencies of RobotVacuumService by two services. This will give us the following:

public class RobotVacuumService { 
    public RobotVacuumService(
        ILoggerService logger,
        IMotorService motorService,
        ILidarService lidarService,
        ICleaningService cleaningService
    )
    {
        // initializations   
    }
}

Not only does this make it cleaner and easier to understand, we can unit test this more easily. It also allows us to follow the single responsibility principle more closely as we make it easier for the service to be understood.