SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
MELHORANDO SEU
CÓDIGO
Law of Demeter
Tell,
don’t ask
Sobre mim
@nelson_senna
https://nelsonsar.github.io
DRY?
YAGNI?
SOLID?
TELL DON’T ASK
LAW OF DEMETER
DDD!
–Alan Kay
“The key in making great and growable
systems is much more to design how its
modules communicate rather than what
their internal properties and behaviors
should be.”
class Paperboy
attr_reader :wallet
def initialize(wallet)
@wallet = wallet
end
def receive_from(customer, amount)
if customer.wallet.try(:amount).to_f > amount
@wallet.amount = amount
customer.wallet = customer.wallet.amount - amount
else
nil
end
end
end
class Paperboy
attr_reader :wallet
def initialize(wallet)
@wallet = wallet
end
def receive_from(customer, amount)
if customer.wallet.try(:amount).to_f > amount
@wallet.amount = amount
customer.wallet = customer.wallet.amount - amount
else
nil
end
end
end
class Paperboy
attr_reader :wallet
def initialize(wallet)
@wallet = wallet
end
def receive_from(customer, amount)
if customer.wallet.try(:amount).to_f > amount
@wallet.amount = amount
customer.wallet = customer.wallet.amount - amount
else
nil
end
end
end
–Ruby Science
“Referencing another object’s state
directly couples two objects together
based on what they are, rather than on
what they do.”
DE FORMA PRÁTICA
describe Paperboy do
describe '#receive_from' do
let(:paperboy) { described_class.new(Wallet.new(0)) }
context 'when customer has enough money to pay' do
it 'add due amount to wallet' do
customer = double
allow(customer).to receive(:wallet).and_return(Wallet.new(10))
paperboy.receive_from(user, 5)
expect(paperboy.wallet.amount).to eq(5)
end
end
end
end
describe Paperboy do
describe '#receive_from' do
let(:paperboy) { described_class.new(Wallet.new(0)) }
context 'when customer has enough money to pay' do
it 'add due amount to wallet' do
customer = double
allow(customer).to receive(:wallet).and_return(Wallet.new(10))
paperboy.receive_from(user, 5)
expect(paperboy.wallet.amount).to eq(5)
end
end
end
end
describe Paperboy do
describe '#receive_from' do
let(:paperboy) { described_class.new(Wallet.new(0)) }
context 'when customer has enough money to pay' do
it 'add due amount to wallet' do
customer = double
allow(customer).to receive(:wallet).and_return(Wallet.new(10))
paperboy.receive_from(user, 5)
expect(paperboy.wallet.amount).to eq(5)
end
end
end
end
E ISSO TEM UM
CHEIRINHO…
–Reek doumentation
“Feature Envy occurs when a code fragment
references another object more often than it
references itself, or when several clients do the
same series of manipulations on a particular type of
object.”
NÃO SE CONVENCEU?
def associate_user
@order ||= current_order
if try_spree_current_user && @order
if @order.user.blank? || @order.email.blank?
@order.associate_user!(try_spree_current_user)
end
end
end
TELL, DON’T ASK
–Martin Fowler
“It reminds us that rather than asking an
object for data and acting on that data,
we should instead tell an object what
to do.”
class Order
def apply_discount(promotion)
if promotion.eligible?(shipment)
promotion.activate(shipment)
end
end
end
class Order
def apply_discount(promotion)
if promotion.eligible?(shipment)
promotion.activate(shipment)
end
end
end
LAW OF DEMETER
–Ruby Science
“The law restricts how deeply a method
can reach into another object’s dependency
graph, preventing any one method from
becoming tightly coupled to another
object’s structure.”
class Paperboy
attr_reader :wallet
def initialize(wallet)
@wallet = wallet
end
def receive_from(customer, amount)
if customer.wallet.try(:amount).to_f > amount
@wallet.amount = amount
customer.wallet = customer.wallet.amount - amount
else
nil
end
end
end
class Paperboy
attr_reader :wallet
def initialize(wallet)
@wallet = wallet
end
def receive_from(customer, amount)
self.wallet.add(customer.pay(amount))
end
end
NULL OBJECT
–Martin Fowler
“Instead of returning null, or some
odd value, return a Special Case that
has the same interface as what the
caller expects.”
def associate_user
@order ||= current_order
if try_spree_current_user && @order
if @order.user.blank? || @order.email.blank?
@order.associate_user!(try_spree_current_user)
end
end
end
def try_spree_current_user
if respond_to?(:spree_current_user)
spree_current_user
elsif respond_to?(:current_spree_user)
current_spree_user
else
Guest.new
end
end
DESVANTAGENS E
CUIDADOS
https://github.com/troessner/reek
PRINCÍPIOS DEVERIAM
AJUDAR E NÃO
CONFUNDIR
DÚVIDAS
REFERÊNCIAS
• http://www.dan-manges.com/blog/37
• http://www.virtuouscode.com/2011/06/28/do-or-do-not-there-is-no-try/
• http://gmoeck.github.io/2011/09/28/why-you-should-care-about-information-hiding.html
• http://blog.davidchelimsky.net/blog/2006/11/27/fighting-the-urge-to-ask/
• http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
• martinfowler.com/bliki/TellDontAsk.html
• https://adamcod.es/2013/11/22/tell-dont-ask.html
• https://pragprog.com/articles/tell-dont-ask
• https://edelpero.svbtle.com/most-common-mistakes-on-legacy-rails-apps
• http://www.mockobjects.com/2006/10/tell-dont-ask-and-mock-objects.html
• https://robots.thoughtbot.com/tell-dont-ask
• https://skillsmatter.com/skillscasts/8611-tell-dont-ask
• https://www.javacodegeeks.com/2015/11/tell-dont-ask.html
• http://natpryce.com/articles/000777.html
REFERÊNCIAS
• http://martinfowler.com/bliki/GetterEradicator.html
• http://verraes.net/2014/09/objects-as-contracts-for-behaviour/
• https://medium.com/skyfishtech/retracing-original-object-oriented-
programming-f8b689c4ce50#.yk9k1s7ku
• http://brightonruby.com/2016/the-point-of-objects-john-cinnamond/
• https://github.com/spree/spree/blob/master/core/app/models/spree/
promotion_handler/page.rb
• https://github.com/troessner/reek/blob/master/docs/Feature-
Envy.md

Mais conteúdo relacionado

Semelhante a Melhorando seu código com Law of Demeter e Tell don't ask

How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018Mike Harris
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2Vishal Biyani
 
Talking to strangers causes train wrecks
Talking to strangers causes train wrecksTalking to strangers causes train wrecks
Talking to strangers causes train wrecksmtoppa
 
The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)Matthias Noback
 
The Quest for Global Design Principles
The Quest for Global Design PrinciplesThe Quest for Global Design Principles
The Quest for Global Design PrinciplesMatthias Noback
 
Webinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with SolrWebinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with SolrLucidworks
 
The well tempered search application
The well tempered search applicationThe well tempered search application
The well tempered search applicationTed Sullivan
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Miguel Gallardo
 
Lazy, Lazy, Lazy all the things !
Lazy, Lazy, Lazy all the things !Lazy, Lazy, Lazy all the things !
Lazy, Lazy, Lazy all the things !Shaunak Pagnis
 
apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...
apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...
apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...apidays
 
The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016Matthias Noback
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsPatchSpace Ltd
 
Microservices Coordination using Saga
Microservices Coordination using SagaMicroservices Coordination using Saga
Microservices Coordination using SagaEran Levy
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibilitymachuga
 
De constructed-module
De constructed-moduleDe constructed-module
De constructed-moduleJames Cowie
 
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
 

Semelhante a Melhorando seu código com Law of Demeter e Tell don't ask (20)

How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
How I Learned to Stop Worrying and Love Legacy Code - Ox:Agile 2018
 
Learning puppet chapter 2
Learning puppet chapter 2Learning puppet chapter 2
Learning puppet chapter 2
 
Talking to strangers causes train wrecks
Talking to strangers causes train wrecksTalking to strangers causes train wrecks
Talking to strangers causes train wrecks
 
The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)
 
The Quest for Global Design Principles
The Quest for Global Design PrinciplesThe Quest for Global Design Principles
The Quest for Global Design Principles
 
Webinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with SolrWebinar: Simpler Semantic Search with Solr
Webinar: Simpler Semantic Search with Solr
 
The well tempered search application
The well tempered search applicationThe well tempered search application
The well tempered search application
 
ETL into Neo4j
ETL into Neo4jETL into Neo4j
ETL into Neo4j
 
Clean Code
Clean CodeClean Code
Clean Code
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
 
Lazy, Lazy, Lazy all the things !
Lazy, Lazy, Lazy all the things !Lazy, Lazy, Lazy all the things !
Lazy, Lazy, Lazy all the things !
 
apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...
apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...
apidays LIVE Jakarta - The shell game called eventual consistency by Dasith W...
 
The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016The quest for global design principles - PHP Benelux 2016
The quest for global design principles - PHP Benelux 2016
 
Uses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & StubsUses & Abuses of Mocks & Stubs
Uses & Abuses of Mocks & Stubs
 
Microservices Coordination using Saga
Microservices Coordination using SagaMicroservices Coordination using Saga
Microservices Coordination using Saga
 
Objects, Testing, and Responsibility
Objects, Testing, and ResponsibilityObjects, Testing, and Responsibility
Objects, Testing, and Responsibility
 
Naming Things
Naming ThingsNaming Things
Naming Things
 
De constructed-module
De constructed-moduleDe constructed-module
De constructed-module
 
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.
 

Mais de Nelson Senna do Amaral

Mais de Nelson Senna do Amaral (9)

Veni vedi vici.
Veni vedi vici.Veni vedi vici.
Veni vedi vici.
 
Pague o aluguel
Pague o aluguelPague o aluguel
Pague o aluguel
 
Dando nome aos códigos
Dando nome aos códigosDando nome aos códigos
Dando nome aos códigos
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
Domínio: Dividir e conquistar
Domínio: Dividir e conquistarDomínio: Dividir e conquistar
Domínio: Dividir e conquistar
 
Interfaces - Como os objetos deveriam se comportar
Interfaces - Como os objetos deveriam se comportarInterfaces - Como os objetos deveriam se comportar
Interfaces - Como os objetos deveriam se comportar
 
Nossa experiência com TDD
Nossa experiência com TDDNossa experiência com TDD
Nossa experiência com TDD
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Tirando o coelho da cartola: integrando sistemas com RabbitMQ
Tirando o coelho da cartola: integrando sistemas com RabbitMQTirando o coelho da cartola: integrando sistemas com RabbitMQ
Tirando o coelho da cartola: integrando sistemas com RabbitMQ
 

Último

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Último (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 

Melhorando seu código com Law of Demeter e Tell don't ask