Design Patterns: Facade

What are Design Patterns?

Most of you already know what a design pattern is, but I want to make sure this blog is accessible to everyone.  A design pattern is a set of “best practices” for how to structure your code to solve certain problems.  It is not a completed library that you an plug in to your code base, but more like a template helping you determine how to structure the code you are writing.

There are a couple of good books out there describing Design Patterns.  The one most people will point you to is the Gang of Four (Design Patterns: Elements of Reusable Object-oriented Software) book.  I know it is probably blasphemy to admit, but I have actually not read that one…I have, however, read the Head First Design Patterns book and I highly recommend it.

Today we are going to dive into the Facade pattern.

Facade Pattern

The definition of the word facade helps me remember what this pattern is used for:

  • an outward appearance that is maintained to conceal a less pleasant or creditable reality.

We often use the facade pattern to hide either a complex part of the system (or subsystem) or to simplify the use of some subsystem. And, sometimes we use it to simply hide a subsystem, third-party library, etc.

It is obvious why we want to create a class that understands the complexity of a subsystem and keep that complexity out of the other parts of your code.  However, it is probably less obvious why you would want to simply hide a subsystem or third-party library behind a facade.

If you hide your subsystem, or third-party library behind a facade, it will allow you to more easily switch this system out for a new one, or even a new version without having to do major refactoring.  If there is only one place that is dealing with this system, there is only one place where you need to make changes.

Secondly, using a facade can help you to mock out systems that you interact with for testing.  Sometimes it can be difficult to fake out a system you are interacting with, but if every part of your system uses the facade, then you simply have to mock out the facade in the rest of the application, and only worry about figuring out how to mock the real system out for the tests around the facade.

 

Lastly, when you hide things behind a facade it allows you to delay making major architectural decisions.  You can determine what you want the API to this system to look like, and even fake out the interactions until you have had a chance to decide how you want to implement the subsystem.

* Photo by Zacharie Gaudrillot-Roy

Hiding utilities behind a facade

Recently, at work, I got into a passionate discussion about whether we should hide things like StringUtils behind a facade.

I was helping a coworker add some tests around a monstrous method and noted that it used StringUtils static methods quite a few times in the method.  Initially I thought that this was a utility class that we had written, so rather than changing the class to have non-static methods, I opted to try to hide it behind a facade (in this case it was a simple pass-through object, but the methods on this object were non-static, thus allowing me to mock it with Mockito).  Upon investigation, it turned out we were using commons.lang StringUtils.  Still, I thought it might be good to put it behind a real object so we could mock it out.

I explained to my colleague that the reason I wanted to do this was so that we didn’t have to set up our tests with realistic data.  We could pass in very fake data and we could make sure that we were only testing the method in question (which was VERY important since it was a behemoth).  By putting it behind the facade, we were able to make it return whatever we wanted.

We spent the morning getting this all set up and she was ready to start off on her own in the afternoon.  Later that afternoon, she was talking with the other developer (and our boss), who works in the code base in question regularly about the tests she was writing.  He did not agree at all about us mocking out StringUtils.

A very heated discussion ensued.  In the end, since I didn’t work in the code in question, I left it up to them how they wanted to test it.

After the discussion, I was reflecting on why I felt so strongly about mocking out StringUtils, and I think I have pinpointed some of the reasons.

  1. The method under test was doing a LOT of things, including calling out to StringUtils nearly a dozen times for different things.  By mocking out StringUtils I felt more comfortable that we were tackling the code that was in the method without having to worry about what StringUtils was going to do with the data we passed it.  I was trying to reduce the complexity of the method in question by ensuring I was using things I had complete control of.
  2. I saw StringUtils as a collaborator and wanted to make sure that I was testing only the method in question, and not the collaborating code.  I believe I saw it this way due to point 1.
  3. I knew that we had some other classes in the code base that had a bunch of static methods on them.  I would treat these the same way.  Rather than treating each different class with static methods differently based on some gut feeling, I wanted to be consistent and treat any class that offered static methods the same way.  This allows me to focus on the tests, rather than spending mental cycles on deciding whether this particular things should be mocked or not.
  4. Hiding a 3rd party tool behind a facade is a best practice I have heard many times.  It allows you to swap out the tool for a new one with little effort.  It can also make it much easier to upgrade to a new version, even if the new version has changed the API, since if everyone using it is actually using the facade, you only need to make the change in one place, and everyone else just continues using the facade in the same way as they always had.

 

 

Simply refactoring the monolithic method into smaller methods that could do each individual task would have left me testing it much differently.

Design Principle: Encapsulate what changes

Principle

Encapsulate or isolate the parts of your system that change more often.

We can accomplish isolation in many different ways.  For example, we can simply separate out the parts of the code (or objects) that are likely to change into separate classes.

Another option that comes to mind is configuration files (or any type of external configuration).  These can include data (like a copyright notice) that might change depending on the deployment, as well as feature switches, or information on which style of a class to load.

Concerns

Shouldn’t I keep the behaviors of an object together in one class, rather than separating it out?

Yes.  However, isolating the parts that change doesn’t need to mean that your object doesn’t define what behaviors it has.

We use helper methods all of the time.  Sometimes it is to perform a calculation that we need to perform in many different places.  When we use a helper class to do some of this work, we will define a method on our object of interest, and have it simply call through to our helper.

For Example:

public class InterestingObject {
   private HelperObject helper;
   public InterestingObject(HelperObject helper) {
      this.helper = helper;
   }

   public void interestingFunctionality() {
      helper.interestingFunctionality();
   }
}

public class HelperObject {
   public void interestingFunctionality() {
      // some interesting functionality here
   }
}

When working with our InterestingObject, we now know that it has interestingFunctionality.  When working with that object, we don’t need to care that there is a helper object that is implements that functionality.

Why does it matter if I change some parts of a class more often than other parts?

First of all, making modifications to a class violates the open/closed principle which states that we should have our classes open to extension but closed to modification.  Granted, it is not always possible to follow this principle.

Imagine you have a class that has behaviors.  In that class, you will likely have some instance variables that you share in several methods.  Now, imagine that you need to change the data structure for one of those variables because you need it in a more convenient form for a new calculation.  In order to switch that data structure, you will need to touch all of the methods that use that data.  If, however, that method lived in a different object it would be free to use a new data structure to do the computation, as long as the API remained the same and it could still return the same type of object/data structure.

What I am getting at with all of those words is that methods inside a class can often be tightly coupled with one another, and that is ok.  However, when you need to touch one, you often have to touch others.  If you have those methods in separate classes, you can often get away with making a change just to the methods in question without having to touch the calling code.

What is all of this work really buying me?

Ideally this is buying you a safety net.  It is allowing you to ensure that the changes you make are only going to impact a small piece and only the piece that you intend.

If you have pulled out some things into a configuration file or table, you can often make changes to your application without even having to rebuild it.  Just make a change to the configuration and restart and viola!

 

How thin is too thin?

I recently had a conversation with a coworker about where the logic belonged in a piece of code.  I felt that his dao* (data access object) layer had too much logic.  I suggested that the objects that were communicating with the database should only have the queries needed to get the data from the database, and any business logic should be in a different layer (likely a service layer). My colleague said that he had done that before and he thought that made the dao layer too thin.

I let the comment slide, and let the code slide (though I am regretting that decision).  But, that got me to wondering if there is such a thing as a layer being “too thin”.

tomatoes
This, by the way, is probably too thin.

The only example I can think of where I might say that a layer was too thin was if it were just a wrapper around another object and it wasn’t really serving any purpose, it just called through to the object it wraps.  However, if the wrapper was serving a purpose (like wrapping a utility object that was all static methods so we can mock it, or wrapping a third party library that we want to encapsulate to make it easy to change out), then I wouldn’t have an issue.

In my mind, I try to think of each layer as a different level of abstraction.  Our controllers have the highest level of abstraction.  Reading the code there helps you understand the high level tasks we need to do (like, get some data, set some values and return some data).

The next level down is the service layer.  This contains business logic  It would contain the code that sets values, or does some calculations that we need to return to the user through the controller.  This layer is more detailed, but will often use other classes to assist.

The last level is the dao layer.  This is where we are getting our data, either from a database or file, or magic 8-ball.  This has nitty-gritty details of how to get the data, but contains NO logic for converting the data in any way.  It can contain queries that allow us to bring back only the data we are interested in.  Those queries can do things for us like sorting our data, etc.  But, the dao layer is simply in charge of executing the queries and returning the data to the service layer.

Do you have any examples where you have seen a layer and thought it was too thin?

*A data access object is any object that is used for accessing data, such as code to talk to a database, or read from a file.  It is a commonly used Design Pattern.  Look forward to a future post about this.