Building Reusable Object-Oriented Systems: Composition

Joël Quenneville

In two recent posts, we’ve used single inheritance and multiple inheritance to build an API client that fetches directors from a fictional movie-facts.com API. Sometimes we read from a cache instead of making HTTP requests and sometimes we need to make multiple requests to a paginated feed and combine them into a de-paginated set.

Let’s take a completely different approach to solving the problem. Instead of building up a single object that does all of the things via inheritance, we are going to cut it up into several smaller object focused on a single responsibility and combine them together via composition.

Client

The client is a high-level object that creates Director instances based on data from the API. It is not concerned with how to make requests or de-paginate them, instead leaving that work up to other objects that are passed in.

module MovieFacts
  class Client
    def initialize(driver, depaginator)
      @driver = driver
      @depaginator = depaginator
    end

    def directors
      fetch_data("/directors").map { |director| Director.new(director) }
    end

    def director(name)
      Director.new(fetch_data("/directors/#{name}"))
    end

    private

    def fetch_data(path)
      @depaginator.depaginate @driver.fetch_data(path)
    end
  end
end

Driver

This object is concerned with the nuts and bolts of fetching the data. There are multiple implementations, all of which implement the same interface (i.e. they are all duck types of each other).

module MovieFacts
  class HttpDriver
    def fetch_data
      # fetch data over HTTP
      # cache results
    end
  end
end
module MovieFacts
  class CacheDriver
    def fetch_data
      # read data from cache
    end
  end
end

Depaginator

The depaginator is an object that takes paginated data and combines it into a single array. Sometimes we don’t want to de-paginate so we provide a no-op version. Once again, both implementations implement the same interface.

module MovieFacts
  class Depaginator
    def depaginate(data)
      # depaginate the data
    end
  end
end
module MovieFacts
  class NoopDepaginator
    def depaginate(data)
      data # just return the data without de-paginating it
    end
  end
end

Putting it all together

Combining all our pieces together, we have an architecture that looks like:

Composition

This is completely modular and can be extended in any way we wish. There is no fear of combinatorial explosion here. Each responsibility is nicely encapsulated in its own object which means it can be refactored any time without affecting any of the collaborating objects.

  1. Do we need to fetch from a different source? Just create a new driver.
  2. Do we want to convert our multiple pages of data into a lazy stream? Implement a new de-paginator.
  3. Need to do another thing to the data as before turning it into Director objects? Pass in another object to the Client.
  4. Need to refactor the implementation of one of the objects? Do so without fear. The only dependency between them is the public interface.

Decorators

We’ve blogged about decorators in the past. They exist in a weird spot between inheritance and composition. You could even say that they use composition to implement inheritance.

Decoration allows you to layer on functionality, building up an object that responds to methods provided the inner object and all of the decorators. Because any decorator can be layered on top of any other decorator we are safe from combinatorial explosion. We also have encapsulation between each of the layers since they can only communicate to each other via each other’s public interface.

We could modify the composition-based implementation above to use decoration:

The client now just takes in an object that responds to fetch_data. That could be a driver or a driver that’s been decorated with the depaginator.

module MovieFacts
  class Client
    def initialize(driver)
      @driver = driver # may or may not be decorated with a depaginator
    end

    def directors
      @driver.fetch_data("/directors").map { |director| Director.new(director) }
    end

    def director(name)
      Director.new(@driver.fetch_data("/directors/#{name}"))
    end
  end
end

The drivers would stay the same as before. The depaginator is turned into a decorator. We no longer need a NoopPaginator because we can get the same effect by passing in an undecorated driver.

module MovieFacts
  class Depaginator < SimpleDelegator
    def fetch_data(path)
      data = __get_obj__.fetch_data(path)
      # depaginate the data
    end
  end
end

Advantages and limitations

A composition-based approach allows us to build smaller, self-contained objects that respect encapsulation, and can be endlessly combined with each other to solve the combinatorial explosion problem.

Composition’s main strength, combining small objects, is also its greatest weakness. Combining many small objects can be a lot of work. Taken to an extreme, you need to create dedicated factory objects just to figure out which objects to combine with each other. Although you’ve made each individual object easier to understand because it stands on its own and is small, inderection is increased in the system overall as you try to follow the execution path of a method from one collaborator to the next.

Further Reading

This article is part 3 of 4 in a series on building reusable object-oriented software.

  1. Simple Inheritance
  2. Mixins/Multiple Inheritance
  3. Composition (this article)
  4. Composition vs Inheritance