Managing Dependencies - Part 2 (OOP)

Last post we looked at dependencies and isolating them. This post we are going to work through some exercises.

Please fix the code below to in line with the principles taught in the last post:


# key assumptions: TomBrady is a class that you 
# don't own, nor do you have controll over it
# and TomBrady's public methods are more
# than likely to change. How would you
# clean up this class?

class NewEnglandPatriots
    def initialize()        
    end    

    def play_1
        qb = TomBrady.new()
        qb.pass
        qb.run_ball
    end

    def play_2
        qb = TomBrady.new()
        qb.pass_to_kicker
        qb.punt
    end

    def play_3
        qb = TomBrady.new()
        qb.pass
        qb.punt
    end
end

  1. First would be to inject TomBrady, so you are not dependent on that particular class. Then you can use other types which share TomBrady’s interface.
  2. If you couldn’t inject, then the next best thing would be to isolate the creation of the Brady instance.
  3. After that, would be to isolate the calling of Brady’s methods. When ever you write qb.punt you are sending a message to someone other than self. You can isolate that to send messages only to self - especially if those methods are likely to change. DRY.
# you should end up with sum-thing that 
# looks like this # ArtAttack

class NewEnglandPatriots
    attr_accessor :qb
    def initialize(qb)
        @qb = qb
    end

    def play_1
        pass
        run_ball
    end

    def play_2
        pass_to_kicker
        punt
    end

    def play_3
        pass
        punt
    end

# label private because they are liable to 
# change based on the dependency to qb
private
    def pass    
        @qb.pass
    end

    def run_ball
        @qb.run_ball
    end

    def punt
        @qb.punt
    end

    def pass_to_kicker
        @qb.pass_to_kicker
    end
end


# if anything changes, you don't
# have to change it in 50 billion places
# also you can easily substitute
# TomBrady for other quarterbacks.

# if you couldn't inject then you gotta isolate
# the creation of the TomBrady class.

# If Tom Brady is more likely to change
# than the Patriots, then perhaps it might
# be better if Brady calls the patriots.
# that way Brady will be relying on a
# dependency that changes less often that 
# he does.

Some food for thought. I hope it helps you.

Written on May 28, 2017