SlideShare uma empresa Scribd logo
1 de 35
TDD Com princípios OO é mais fácil
TDD – Test Driven Development
Invertemos a ordem
Teste antes da implementação
Como fazer?
Mantra Vermelho – Verde - Refatoração
 
 
Refatoração
TDD não é difícil...
Código Testável
Princípios OO
SRP  (Single Responsibility Principle)
 
 
Duas razões para mudar
 
Separar responsabilidades: Dia e Mês
 
 
 
DIP (Dependency Inversion Principle)
 
 
 
Dependência de uma classe específica  (OperadoraVisa)
 
Depender da abstração
 
 
Podemos criar um ambiente para testes
 
 
Não é só isso DRY - Don’t Repeat Your Self Open Closed Principle Lei de Demeter Interface Segragation Principle
Obrigado! @alexchastinet [email_address]

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

TDD com OO é mais fácil

Notas do Editor

  1. TDD foi criado por Kent Beck, autor da conhecida metodologia ágil XP. TDD é um elemento essencial do XP.
  2. Basicamente, em TDD nos modificamos um pouco a ordem do desenvolvimento.
  3. Escreva um teste com o comportamento que vc imagina que será atendido. Ex.: calcular o total de horas de um período
  4. Implemente o código para que ele teste passe o mais rápido possível. Pode cometer pecados nessa parte...
  5. Refatore o código, remove duplicações e os pecados cometidos na fase anterior.
  6. Normalmente, programar com TDD não é difícil. Porém requer disciplina. O problema é que estamos acostumados a partir direto para a solução sem pensar muito nas decisões que tomamos enquanto implementamos. Para fazer TDD corretamente, precisamos de alguns conhecimentos que vão nos ajudar escrever um código mais “testável”.
  7. Um código “testável” tem: 1 - responsabilidades bem definidas -> é fácil entender o objetivo da classe 2 – flexibilidade -> é possível isolar as unidades testadas substituindo dependências complexas Veremos alguns conceitos podem nos ajudar a alcançar um código assim...
  8. Recorrer a princípios básicos da orientação a objetos pode nos ajudar a criar um código mais testável.
  9. Princípio da responsabilidade única O que seria responsabilidade? -> muito genérico Toda classe deve ter um, e somente um, motivo para ser modificada Exemplo...
  10. FolhaDePonto precisa calcular a carga horária do mês ...
  11. Só que também está calculando a carga horária do dia...
  12. FolhaDePonto tem duas razões para ser modificada -> quebra do SRP -> carga horária do mês -> carga horária do dia
  13. Devido ao alto nível de acoplamento (o calculo está sendo feito internamente), não temos como testar de forma eficiente o cálculo da carga horária
  14. Vamos aplicar o princípio SRP e separar as responsabilidades que encontramos -> Dia e Mês
  15. A classe dia é responsável por calcular a carga horária do dia
  16. A classe mês é responsável por calcular a carga horária do mês
  17. Agora podemos testar o cálculo da carga horária do dia de forma simples
  18. Princípio da Inversão de Dependência -> Um módulo de alto nível não deve depender de um módulo de baixo nível, ambos devem depender de abstrações. Exemplo...
  19. O sistema de controle de pagamento deve validar uma compra se o cartão for valido. Ele depende de uma operadora de cartão para aprovar o pagamento.
  20. Ele depende de uma operadora de cartão para aprovar o pagamento e realizar a transação.
  21. A classe da Operadora de cartões se comunica com um servidor específico para realizar as transações de compras.
  22. O módulo ControleDePagamento depende diretamente de uma módulo de baixo nível (OperadoraVisa) -> quebra do DIP
  23. Problema -> Devido a este forte acoplamento, todos os testes irão se comunicar com o servidor e realizar transações reais!! ..Imagine o prejuízo...
  24. Solução -> ao invés de dependermos de uma representação específica da operadora de cartões, vamos criar uma dependência de uma abstração da operadora de cartões e recebê-la por parâmetro.
  25. Removemos a dependência para a classe...
  26. ... e recebemos uma instancia da abstração por parâmetro no construtor
  27. Agora o código está mais flexível, dessa forma podemos substituir uma classe de operadora de cartão real por uma classe falsa para o ambiente de testes.
  28. Criamos uma classe falsa, que se comporte como uma operadora mas que ñ realize operações reais. -> Está de acordo com a abstração da operadora de cartões de crédito.
  29. Agora podemos testar sem correr o risco de ter um prejuízo de R$ 1000 toda vez que o teste for executado...
  30. Outros princípios que podem nos ajudar a escrever um código mais testável DRY -> Don´t Repeat Your Self -> não se repita: remova duplicações do código YAGNI -> You Gonna need it -> não acrescente complexidade desnecessária Lei de Demeter -> evite os “vagões de trem” nos código -> carro.motor.iniciar_rotacao => carro.ligar