Be a Developer, not a Blender

Loose Coupling

When your class is communicating with a lot of other classes we say that your class has a High Coupling. Typically we find two types of coupling:

  1. Frameworks: it is easy to find framework related imports. In a Spring Controller it is usual to find 8 imports regularly.
  2. Business: Happens when our class is used across the whole system. Imagine a “StringUtill” class that will be used in several parts of the project

The problem of High Coupling will appear when you need to evolve your code. Imagine that we have the PersonService class with a service that need to count all the dogs in the system, the PersonService class will not access the DAO/Repository directly:

PersonService —> DogService.count() —> DogRespository.count()

Imagine now that the DogRespository.count() will receive now a value that will be used for pagination, but the 0 (zero) value would be valid for 99% of the current queries. All the methods that invoke the repository directly would needed to be refactored, and with the update would look like DogRespository.count(0). PersonService is invoking the count() method through the DogService class; we could update only the DogService class and keep the other classes intact.

public class DogService{
    public long count() {
        return dogRepository.count(0);
    }
}

When we encapsulate/hide our classes we can do several kind of refactorings without reflexions of this to the other parts of the system.

Facade is a Good Call

Facade is a good pattern to loose coupling. Take a look at the code below:

public class Car {
    public void turnEngineOn() {
        EngineTemperature.check();
        RadiatorTemperature.check();
        WindowTemperature.check();
        startEngine();
    }
}

Notice that we have 3 classes to do a temperature validation and all the 3 classes will be coupled to every method that needs to do these validations.

The Facade pattern was created to simplify these kind of situations that we could group those validations into just one. The code above could be refactored to:

public class Car {
    public void turnEngineOn() {
        TemperatureFacade.check();
        startEngine();
    }
}

With the Facade we decoupled 3 classes and now only one will be used. Now it is easier for the developer to invoke the required validations; it is easier to do a refactoring because the classes are “hidden”.

Conclusion

It is not a good practice to spread all your business classes across the project. Do not use a Facade/Service class inside a DAO, it will be crossing layers. Facade is a good pattern and will make your project easier to use.

2 thoughts on “Be a Developer, not a Blender

Leave a Comment