DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Building Reusable Object-Oriented Systems: Composition

Building Reusable Object-Oriented Systems: Composition

Learn an approach to reading from caches that combines modularity and the single responsibility principle — composition.

Joel Quenneville user avatar by
Joel Quenneville
·
Nov. 20, 16 · Tutorial
Like (3)
Save
Tweet
Share
6.61K Views

Join the DZone community and get the full member experience.

Join For Free

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 objects 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.

Object (computer science)

Published at DZone with permission of Joel Quenneville, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Should You Know About Graph Database’s Scalability?
  • Kotlin Is More Fun Than Java And This Is a Big Deal
  • Load Balancing Pattern
  • Last Chance To Take the DZone 2023 DevOps Survey and Win $250! [Closes on 1/25 at 8 AM]

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: