DI in ruby

14

Click here to load reader

Transcript of DI in ruby

Page 1: DI in ruby

Dependency injection in ruby

@huydx

Page 2: DI in ruby

what is depedency injection

(DI)

Page 3: DI in ruby

dependency: a part of your code "use" another part

dependency injection: how you inject a part of your code in another part

Page 4: DI in ruby

Some examples

Page 5: DI in ruby

example class Train attr_accessor :food_service, :drink_service

def initialize(food_service, drink_service) @food_service = food_service @drink_service = drink_service end

def serve(customer = Customer.new) customer.eat(food_service.make_food) customer.drink(drink_service.make_drink) customer.sleep end end

Page 6: DI in ruby

example class Train attr_accessor :food_service, :drink_service

def initialize(food_service, drink_service) @food_service = food_service @drink_service = drink_service end

def serve(customer = Customer.new) customer.eat(food_service.make_food) customer.drink(drink_service.make_drink) customer.sleep end end

Train depends on food service and drink service

Train depends on customer

Page 7: DI in ruby

You already use it everyday!

Page 8: DI in ruby

Some "ruby" ways:

- constructor (initialize) - parameter passing - module include / extend - inheritance

Page 9: DI in ruby

Disadvantages

- constructor (initialize)+ parameter passing:

api changes -> parameter changes

Page 10: DI in ruby

Disadvantages

- module include / extend

poison method call space, sometimes you don't know what is included??!!

Page 11: DI in ruby

Disadvantages

- inheritance

create once, stick forever!! Parent API/interface needed to be carefully design

Page 12: DI in ruby

Another DI approach (not ruby way):

- Use DI framework - define dependencies in configuration file - found https://github.com/dsawardekar/encase

Point: is it really needed??

Page 13: DI in ruby

Point is: why do you need to care about DI?

Page 14: DI in ruby

Some points:

- Testability - Loosely coupled - Code extensibility