What is a dependency?

A dependency is when an object knows something about another object. Single purpose classes produce objects with a narrow range of capabilities, so objects must work together and know stuff about each other to solve problems and some dependencies are inevitable. However, the dependencies between classes must be managed or the application’s objects will behave as one intertwined object and the code will be difficult to extend or maintain.

In the following example, the Company class depends on the Person class.

class Company
  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name

  def introduce_ceo
    ceo = Person.new(@first_name, @last_name)
    "Our company is led by #{ceo.first_name} #{ceo.last_name}"

The Company class knows the name of the Person class and knows that it must be initialized with first_name and last_name Strings, with first_name first, followed by last_name. Company also knows that instances of the Person class will respond to the first_name and last_name messages. Company is heavily dependent on Person, so simple changes to the Person class can break the Company class.

For example, adding an additional initialization variable to the Person class will break the Company class:

class Person
  def initialize(first_name, last_name, date_of_birth)
    @first_name = first_name
    @last_name = last_name
    @date_of_birth = date_of_birth

The Company class needs to know some things about the Person class, so some dependencies are required, but this code has unnecessary dependencies that make the Company class brittle. We have demonstrated that even small changes to the Person class will break the Company class. In subsequent posts, we will review dependency injection, dependency isolation, argument-order dependencies, and reversing dependency direction to manage dependencies and keep classes separate so small changes in one class do not cascade throughout the application.

* This post, as well as several other posts on this site, is inspired by Practical Object-Oriented Design in Ruby by Sandi Metz.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s