o9s
is a microblog
home archives search feed blogroll


Refactor Freely, Use A Facade

class Engine {
  void start();
  void stop();
}
class Wheel {
  void turn(int degree);
}
class Brake {
  void apply();
}

Consider the library above. You designed a car. You avoided creating a god object. Good job! But oh no, the API is not as intuitive as you might have liked. Your users will have to figure out where every feature resides. For example, if they want to turn the car around, they will have to sift through your documentation to figure out you placed the turn method in Wheel. They will have to call Wheel.turn(180).

Now let’s say you don’t like the name Wheel. It’s confusing. Is it a wheel with a pneumatic tire or is it a steering wheel? You meant a steering wheel. You decide to rename the class to SteeringWheel. Your code is now more obvious. Good job! But oh no, you’ve broken the code of people that use your library. They call Wheel.turn(180), but what they should call now is SteeringWheel.turn(180).

You can fix all your problems with a simple design pattern. You should implement a facade. A facade is a class that sits in front of your complex architecture.

class CarFacade {
  Engine engine = new Engine();
  Wheel wheel = new Wheel();
  Brake brake = new Brake();

  void startEngine() {
    engine.start();
  }

  void stopEngine() {
    engine.stop();
  }

  void turnWheel(int degree) {
    wheel.turn(degree);
  }

  void brake() {
    brake.apply();
  }
}

Tell your users to do every operation through this class.

Your users are happy. They can easily find how to do what they want to do using their code-completion tool. Most of the time, they don’t even need your documentation. But you still wrote documentation because you’re a good programmer. The coupling is greatly reduced, their codebases are not coupled with Engine, Wheel and Brake. Their codebases are only coupled with CarFacade.

You’re happy. When you want to refactor your architecture, you can. You can refactor with a pick axe if you desire. Just don’t touch CarFacades public API.

All facades fall sometime, then the mask comes off and the real heart is seen.” ― Jessiqua Wittman, not a programmer

Posted on 2018-01-26   #designpattern  






← Next post    ·    Previous post →