SlideShare una empresa de Scribd logo
1 de 21
Law of Demeter
Don’t Mess With The Law
‘
@michaelelfassy
Michael Elfassy
Smashing Boxes
Definition
1. Each unit should have only limited knowledge about
other units
2. Each unit should only talk to its friends; don't talk to
strangers.
3. Only talk to your immediate friends.
source: Wikipedia
In other words
An object should only invoke methods of these kind of
objects:
1. itself
2. its parameters
3. any objects it creates
4. its direct component objects
5. objects of the same type*
itself
class User
attr_accessor :first_name, :last_name
def name
"#{first_name} #{last_name}"
end
end
its parameters
def nickname(name)
"#{name[0..2]}o"
end
objects it creates
def total
calculator = Calculator.new
average + calculator.square(mean)
end
direct components
def initialize()
@calculator = Calculator.new
end
def total
average + @calculator.square(mean)
end
objects of the same type*
# String
name.strip.gsub(/^a/,'b').constantize
# ActiveRecord Relation
User.where(...).order
Violations
class User
belongs_to :department
def division_name
department.division.name
end
end
Violations
try().try()
smells bad!
class User
belongs_to :department
def division_name
# we know the user has a department
dep = department
# we're assuming the department has a function called division
# which returns the associated division object
# we're assuming that every department belongs to a division
div = dep.division
# we're assuming the division has a name attribute
division_name = div.name
end
end
Dependency assumption
● Duplication
o Once you traverse in one place you are likely to traverse in another place
● Few places understand the relationships
● Don’t create “context”
● at each step of the traversal, the value
returned is decided by the object being
asked
Following the Law
class User
belongs_to :department
def division_name
# ask the department for a division name (you decide how you are going to get it!)
department.try(:division_name)
end
end
class Department
belongs_to :division
def division_name
# ask the division for a name (you decide how you are going to get it!)
division.name
end
end
The rails way(™)
class User
belongs_to :department
delegate :division_name, to: :department, allow_nil: true
end
class Department
belongs_to :division
delegate :name, to: :division, prefix: true
delegate :director, to: :division
end
Testing
Now we can test models independently without
having to do nested stubs!
I am the law
let’s replace all . with _ !
NO…
Don’t only fix the violations, look at what they
are telling you. Refactor!
Wallet example
class Wallet
attr_accessor :cash
end
class Customer
has_one :wallet
end
class Paperboy
def collect_money(customer, due_amount)
if customer.wallet.cash < due_ammount
raise InsufficientFundsError
else
customer.wallet.cash -= due_amount
@collected_amount += due_amount
end
end
end
paperboy should not be taking cash
out of a customer's wallet
Delegate attributes
class Customer
has_one :wallet
# attribute delegation
def cash
@wallet.cash
end
end
class Paperboy
def collect_money(customer, due_amount)
if customer.cash < due_ammount
raise InsufficientFundsError
else
customer.cash -= due_amount
@collected_amount += due_amount
end
end
end
paperboy doesn’t need to know how much
cash the client has in his wallet
Delegate Behaviour
class Customer
has_one :wallet
# behavior delegation
def pay(amount)
@wallet.withdraw(amount)
end
end
class Paperboy
def collect_money(customer, due_amount)
@collected_amount += customer.pay(due_amount)
end
end
Tell don’t ask
Summary
● It’s a guideline more than a law
● Look for the spirit of the law
● try.try just smells
Hint, it’s not a real gun
Cardboard - CMS / Admin Panel
https://github.com/smashingboxes/cardboard

Más contenido relacionado

Similar a The Law of Demeter

جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Workhorse Computing
 
Melhorando seu código com Law of Demeter e Tell don't ask
Melhorando seu código com Law of Demeter e Tell don't askMelhorando seu código com Law of Demeter e Tell don't ask
Melhorando seu código com Law of Demeter e Tell don't askNelson Senna do Amaral
 
TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...
TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...
TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...tdc-globalcode
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
 
Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesJon Kruger
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Brian Hogan
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsPatchSpace Ltd
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
Nedap Rails Workshop
Nedap Rails WorkshopNedap Rails Workshop
Nedap Rails WorkshopAndre Foeken
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogrammingjoshbuddy
 

Similar a The Law of Demeter (20)

جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.Object Trampoline: Why having not the object you want is what you need.
Object Trampoline: Why having not the object you want is what you need.
 
Melhorando seu código com Law of Demeter e Tell don't ask
Melhorando seu código com Law of Demeter e Tell don't askMelhorando seu código com Law of Demeter e Tell don't ask
Melhorando seu código com Law of Demeter e Tell don't ask
 
TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...
TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...
TDC2016POA | Trilha Ruby - Melhorando seu código com Law of Demeter e Tell do...
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Advanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID PrinciplesAdvanced Object-Oriented/SOLID Principles
Advanced Object-Oriented/SOLID Principles
 
Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7Intro to Ruby - Twin Cities Code Camp 7
Intro to Ruby - Twin Cities Code Camp 7
 
About Python
About PythonAbout Python
About Python
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
S12.s01 - Material TP.pdf
S12.s01 - Material TP.pdfS12.s01 - Material TP.pdf
S12.s01 - Material TP.pdf
 
Values
ValuesValues
Values
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
Nedap Rails Workshop
Nedap Rails WorkshopNedap Rails Workshop
Nedap Rails Workshop
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 

Más de Smashing Boxes

Leverage IoT to Enhance Security and Improve User Experience
Leverage IoT to Enhance Security and Improve User ExperienceLeverage IoT to Enhance Security and Improve User Experience
Leverage IoT to Enhance Security and Improve User ExperienceSmashing Boxes
 
UX and Machine Learning
UX and Machine Learning UX and Machine Learning
UX and Machine Learning Smashing Boxes
 
Bourbon on a Budget with IoT - Pinetop Distillery | RIoT NC
Bourbon on a Budget with IoT - Pinetop Distillery | RIoT NCBourbon on a Budget with IoT - Pinetop Distillery | RIoT NC
Bourbon on a Budget with IoT - Pinetop Distillery | RIoT NCSmashing Boxes
 
The Future of Wearables
The Future of WearablesThe Future of Wearables
The Future of WearablesSmashing Boxes
 
Growth engineering 101: Google Analytics Essentials
Growth engineering 101: Google Analytics EssentialsGrowth engineering 101: Google Analytics Essentials
Growth engineering 101: Google Analytics EssentialsSmashing Boxes
 
What is a Growth Engineer?
What is a Growth Engineer?What is a Growth Engineer?
What is a Growth Engineer?Smashing Boxes
 

Más de Smashing Boxes (6)

Leverage IoT to Enhance Security and Improve User Experience
Leverage IoT to Enhance Security and Improve User ExperienceLeverage IoT to Enhance Security and Improve User Experience
Leverage IoT to Enhance Security and Improve User Experience
 
UX and Machine Learning
UX and Machine Learning UX and Machine Learning
UX and Machine Learning
 
Bourbon on a Budget with IoT - Pinetop Distillery | RIoT NC
Bourbon on a Budget with IoT - Pinetop Distillery | RIoT NCBourbon on a Budget with IoT - Pinetop Distillery | RIoT NC
Bourbon on a Budget with IoT - Pinetop Distillery | RIoT NC
 
The Future of Wearables
The Future of WearablesThe Future of Wearables
The Future of Wearables
 
Growth engineering 101: Google Analytics Essentials
Growth engineering 101: Google Analytics EssentialsGrowth engineering 101: Google Analytics Essentials
Growth engineering 101: Google Analytics Essentials
 
What is a Growth Engineer?
What is a Growth Engineer?What is a Growth Engineer?
What is a Growth Engineer?
 

Último

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Último (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

The Law of Demeter

  • 1. Law of Demeter Don’t Mess With The Law ‘
  • 3. Definition 1. Each unit should have only limited knowledge about other units 2. Each unit should only talk to its friends; don't talk to strangers. 3. Only talk to your immediate friends. source: Wikipedia
  • 4. In other words An object should only invoke methods of these kind of objects: 1. itself 2. its parameters 3. any objects it creates 4. its direct component objects 5. objects of the same type*
  • 5. itself class User attr_accessor :first_name, :last_name def name "#{first_name} #{last_name}" end end
  • 7. objects it creates def total calculator = Calculator.new average + calculator.square(mean) end
  • 8. direct components def initialize() @calculator = Calculator.new end def total average + @calculator.square(mean) end
  • 9. objects of the same type* # String name.strip.gsub(/^a/,'b').constantize # ActiveRecord Relation User.where(...).order
  • 10. Violations class User belongs_to :department def division_name department.division.name end end
  • 11. Violations try().try() smells bad! class User belongs_to :department def division_name # we know the user has a department dep = department # we're assuming the department has a function called division # which returns the associated division object # we're assuming that every department belongs to a division div = dep.division # we're assuming the division has a name attribute division_name = div.name end end
  • 12. Dependency assumption ● Duplication o Once you traverse in one place you are likely to traverse in another place ● Few places understand the relationships ● Don’t create “context” ● at each step of the traversal, the value returned is decided by the object being asked
  • 13. Following the Law class User belongs_to :department def division_name # ask the department for a division name (you decide how you are going to get it!) department.try(:division_name) end end class Department belongs_to :division def division_name # ask the division for a name (you decide how you are going to get it!) division.name end end
  • 14. The rails way(™) class User belongs_to :department delegate :division_name, to: :department, allow_nil: true end class Department belongs_to :division delegate :name, to: :division, prefix: true delegate :director, to: :division end
  • 15. Testing Now we can test models independently without having to do nested stubs!
  • 16. I am the law let’s replace all . with _ ! NO… Don’t only fix the violations, look at what they are telling you. Refactor!
  • 17. Wallet example class Wallet attr_accessor :cash end class Customer has_one :wallet end class Paperboy def collect_money(customer, due_amount) if customer.wallet.cash < due_ammount raise InsufficientFundsError else customer.wallet.cash -= due_amount @collected_amount += due_amount end end end paperboy should not be taking cash out of a customer's wallet
  • 18. Delegate attributes class Customer has_one :wallet # attribute delegation def cash @wallet.cash end end class Paperboy def collect_money(customer, due_amount) if customer.cash < due_ammount raise InsufficientFundsError else customer.cash -= due_amount @collected_amount += due_amount end end end paperboy doesn’t need to know how much cash the client has in his wallet
  • 19. Delegate Behaviour class Customer has_one :wallet # behavior delegation def pay(amount) @wallet.withdraw(amount) end end class Paperboy def collect_money(customer, due_amount) @collected_amount += customer.pay(due_amount) end end Tell don’t ask
  • 20. Summary ● It’s a guideline more than a law ● Look for the spirit of the law ● try.try just smells Hint, it’s not a real gun
  • 21. Cardboard - CMS / Admin Panel https://github.com/smashingboxes/cardboard

Notas del editor

  1. maintainable and adaptable code objects are less dependent on the internal structure of other objects object containers can be changed without reworking their callers.