Responsibility

Object Oriented Design done right.

José Mota

Ruby and Javascript instructor at Tuts+ for 1.5 years

Code Retreats em Portugal


Objectives


  • How OOD is used
  • How it should be used
  • How it helps define responsibilities

Typical case for objects


class User
def buy(product)
# code that makes the user buy a product
end
end

What's wrong in the picture?

Title

class User
def buy(product)
# code that makes the user buy a product
end
end

What does buy do?


  • Updates the stock of the product
  • Deals with a money charge from the user
  • Emails a receipt
  • Engages a whole process of shipping

Solution

Create a new class with the specific

responsibility of handling a purchase.

class User
def buy(product)
Purchase.new(user, product).execute
end
end



class Purchase
def initialize user, product
@user = user
@product = product
end

def execute
update_stock
charge_user
deliver_receipt
engage_shipping
end
end

Feature change

Buy multiple products

What to do?

It breaks the code.

Solution

Create a class that handles multiple products.

class PurchaseMany
def initialize user, products
@user = user
@product = products
end

def execute
@products.each do |product|
Purchase.new(user, product).execute
end
end
end

Demo

Made with Slides.com