SlideShare uma empresa Scribd logo
1 de 45
Test-Driven Development
      Coding Dojo
             Pietro Di Bello
     pietro.di.bello@xpeppers.com
             @pierodibello
               @xpeppers


       JUG Trentino Alto-Adige
            Agosto 2012
Che cos’è il TDD?
è una tecnica di design in cui lo sviluppo di una
funzionalità è guidato dalla scrittura di uno o più unit
test
    • si basa sull'uso di unit test
    • lo sviluppo del codice è guidato dalla scrittura di
      unit test che devono essere di volta in volta verificati
    • il test viene scritto ed eseguito PRIMA del codice
      stesso che consentirà di verificarlo
Write a test
public class AdderTest {
    @Test
    public void testTwoPlusThree() {
        Adder a = new Adder();
        assertEquals(5, a.add(2, 3));
    }
}
Now it compiles
public class AdderTest {
    @Test
    public void testTwoPlusThree() {
        Adder a = new Adder();
        assertEquals(5, a.add(2, 3));
    }
}

public class Adder {
    public int add(int a, int b) { return 0; }
}
Red bar!
public class AdderTest {
    @Test
    public void testTwoPlusThree() {
        Adder a = new Adder();
        assertEquals(5, a.add(2, 3));
    }
}

public class Adder {
    public int add(int a, int b) { return 0; }
}

              Expected 5, was 0
Do the simplest thing
public class AdderTest {
    @Test
    public void testTwoPlusThree() {
        Adder a = new Adder();
        assertEquals(5, a.add(2, 3));
    }
}

public class Adder {
    public int add(int a, int b) { return 5; }
}
Refactor
public class AdderTest {
    @Test
    public void testTwoPlusThree() {
        Adder a = new Adder();
        assertEquals(5, a.add(2, 3));
    }
}

public class Adder {
    public int add(int a, int b) { return a+b; }
}
The procedure

1. Write a test

2. Make it compile
                  Expected 5, was 0

3. Make it pass quickly

4. Refactor to remove duplication
Red

Refactor             Green




   Repeat every 2-10 min.
Clean code that works.
TDD: why?
• Per abbattere la complessità
• Consente di ridurre la soluzione di un problema
  complesso in tanti problemi più semplici (divide et
  impera)
TDD: why?
Ogni test rappresenta una opportunità di porre una
domanda sul sistema, la cui risposta ci porterà ad un
maggiore consolidamento della conoscenza e una
riduzione dell'unknown
TDD: why?
When we write a test, we imagine the perfect
interface for our operation.We are telling ourselves
a story about how the operation will look from the
outside.
Our story won't always come true, but it's better to
start from the best-possible application program
interface (API) and work backward than to make
things complicated, ugly, and "realistic" from the
get-go.
                                          Kent Beck
Simple design

The code is simple enough when it:
   0. Runs all the tests
   1. Contains no duplication
   2. Expresses every idea that we need to express
   3. Has the minimum number of classes and functions
(In this order)
                 Kent Beck, Extreme Programming Explained
Il primo test
• deve essere piccolo
• il più semplice possibile
   • ad es possiamo selezionare un caso
  degenere
• tracciamo i primi contorni di una API ad un
dettaglio molto più fine di quanto siamo abituati
solitamente
Il primo test
Il primo test
Il prossimo test

Trattiamo ogni test come una nuova occasione per
imparare e ridurre la complessità sul modello del
problema

Qual’è la prossima domanda a cui vogliamo rispondere?
Il prossimo test
Uso della to-do list
• Utile per gestire la complessità
 • elencare i diversi aspetti del problema
• NON si elencano i test da implementare
 • non è TDD
• Riduce lo stress
• Bussola per farci capire a che punto siamo e non ci
 perdere la strada
• Se mi viene in mente qualcosa la scrivo nella todolist e
 continuo sulla mia strada senza perdere focus
 • => tecnica del Pomodoro
Coding Dojo
What’s a kata?

A kata is meant to be memorized.
Students of a kata study it as a form, not as a conclusion.
It is not the conclusion of the kata that matters, it's the
steps that lead to the conclusion.
             Bob Martin (http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata)
The Bowling Game Kata
             By Robert Martin “Uncle Bob”




http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata
Il punteggio del bowling

Ci sono 10 frame. In ogni frame il giocatore ha due possibilità di abbattere 10 birilli
  (pins). Il punteggio per il frame è il numero di birilli abbattuti, più i bonus per stike o
  spare.
Uno spare è quando il giocatore abbatte 10 birilli in due tiri. Il bonus per quel frame è il
 numero di birilli abbattuti al tiro successivo. Nel frame 3 dell'esempio, il punteggio è 10
 (i birilli abbattuti) più il bonus di 5 (abbattuti nel tiro successivo.)
Uno strike è quando il giocatore abbatte tutti i birilli in un solo tiro. Il bonus per quel
 frame è il numero di birilli abbattuti nei due tiri successivi
Nel decimo frame, se il giocatore fa uno strike o spare può fare i tiri necessari per
 completare il frame. In ogni caso, al decimo frame non vengono fatti più di tre tiri.
I requisiti

• Scrivete una classe“Game” con due metodi:
 • roll(pins : int) è chiamato ogni volta che il
      giocatore fa un tiro. L’argomento è il
      numero di birilli abbattuti.
  •   score(): int è chiamato quando il gioco
      termina e ritorna il punteggio finale.
Una veloce sessione di design

         Ovviamente avremo bisogno di una classe
         Game.
Una veloce sessione di design


     Un gioco ha 10 frames.
Una veloce sessione di design


                 Un frame ha uno o due birilli (pins)
Una veloce sessione di design




         Il decimo frame è diverso dagli
         altri: può avere due o tre tiri.
Una veloce sessione di design


La funzione score
deve iterare su tutti i
frames e calcolare i
loro punteggi.
Una veloce sessione di design
               Il punteggio di uno spare o di uno strike
               dipende dal punteggio del frame
               successivo
Coding Katas: String
    Calculator


        by Roy Osherove
    (http://osherove.com/tdd-
              kata-1)
StringCalculator Kata
Create a simple String calculator with a method

  int Add(string numbers)

The method can take zero, one or two numbers, and
will return their sum

• for example “” or “1” or “1,2”
• for an empty string it will return 0
Start with the simplest test case of an empty string and
move to one and two numbers
StringCalculator Kata

Remember to solve things as simply as possible so
that you force yourself to write tests you did not
think about

Remember to refactor after each passing test
StringCalculator Kata


Allow the Add method to handle an unknown
amount of numbers
StringCalculator Kata

 Allow the Add method to handle new lines between
 numbers (instead of commas).

• the following input is ok:  “1n2,3”  (will equal
 6)
• the following input is NOT ok:  “1,n” (not need
 to prove it - just clarifying)
StringCalculator Kata
Support different delimiters

to change a delimiter, the beginning of the string will contain a
separate line that looks like this:

“//[delimiter]n[numbers…]”

for example “//;n1;2” should return three where the default
delimiter is ‘;’ .

the first line is optional.

all existing scenarios should still be supported
StringCalculator Kata
Calling Add with a negative number will throw an
  exception “negatives not allowed” - and the
            negative that was passed.

If there are multiple negatives, show all of them in
              the exception message
StringCalculator Kata


Numbers bigger than 1000 should be ignored, so
            adding 2 + 1001 = 2
More on code kata

• http://codekata.pragprog.com/
• http://codingdojo.org/
• https://sites.google.com/site/tddproblems/all-problems-1
• http://xp123.com/articles/tests-from-a-hat/
Homework
Roman Numerals kata:
write a Roman class which converts an integer into a
roman number string.
es: 12 => “XII”

Bonus: can you write the inverse converter (from roman
to integer)?
es: “IX” => 9
Homework

Prime Factors kata:


 • http://butunclebob.com/
   ArticleS.UncleBob.ThePrimeFactorsKata
Supermarket checkout

• Compute the
  total price
• Scan items one
  at a time
• In any order
Copyright 2008-2012
               XPeppers

Tutti i diritti di riproduzione sono riservati.

Mais conteúdo relacionado

Semelhante a A brief intro to TDD for a JUG-TAA event

Linux Day 20091024 Test Driven Development
Linux Day 20091024 Test Driven DevelopmentLinux Day 20091024 Test Driven Development
Linux Day 20091024 Test Driven DevelopmentRoberto Albertini
 
Test Driven Development for iOS
Test Driven Development for iOSTest Driven Development for iOS
Test Driven Development for iOSAlessandro Ceseno
 
Vogliamo programmatori stupidi e pigri!
Vogliamo programmatori stupidi e pigri!Vogliamo programmatori stupidi e pigri!
Vogliamo programmatori stupidi e pigri!Marcello Missiroli
 
TDD patterns and TDD strategies
TDD patterns and TDD strategiesTDD patterns and TDD strategies
TDD patterns and TDD strategiesAlessandro Ceseno
 
Effective Code Transformations in C++
Effective Code Transformations in C++Effective Code Transformations in C++
Effective Code Transformations in C++Marco Arena
 
Test Driven Development @ Xe.Net
Test Driven Development @ Xe.NetTest Driven Development @ Xe.Net
Test Driven Development @ Xe.NetMauro Servienti
 
TypeScript, ovvero JavaScript che "non si rompe"
TypeScript, ovvero JavaScript che "non si rompe"TypeScript, ovvero JavaScript che "non si rompe"
TypeScript, ovvero JavaScript che "non si rompe"BENTOSA
 
Java Unit Testing - Introduction
Java Unit Testing - IntroductionJava Unit Testing - Introduction
Java Unit Testing - Introductionfgianneschi
 
Creare Suite di Test Automatici intelligenti con Selenium IDE
Creare Suite di Test Automatici intelligenti con Selenium IDECreare Suite di Test Automatici intelligenti con Selenium IDE
Creare Suite di Test Automatici intelligenti con Selenium IDEStefano Trojani
 
Mocking Objects Practices
Mocking Objects PracticesMocking Objects Practices
Mocking Objects PracticesGrUSP
 
LINQ, Entities Framework & ORMs
LINQ, Entities Framework & ORMsLINQ, Entities Framework & ORMs
LINQ, Entities Framework & ORMsJUG Genova
 
Algoritmi e Calcolo Parallelo 2012/2013 - Analisi degli Algoritmi
Algoritmi e Calcolo Parallelo 2012/2013 - Analisi degli AlgoritmiAlgoritmi e Calcolo Parallelo 2012/2013 - Analisi degli Algoritmi
Algoritmi e Calcolo Parallelo 2012/2013 - Analisi degli AlgoritmiPier Luca Lanzi
 
Set Based Thinking
Set Based ThinkingSet Based Thinking
Set Based ThinkingDavide Mauri
 
Corso Programmazione Java Base
Corso Programmazione Java BaseCorso Programmazione Java Base
Corso Programmazione Java BaseK-Tech Formazione
 

Semelhante a A brief intro to TDD for a JUG-TAA event (20)

Linux Day 20091024 Test Driven Development
Linux Day 20091024 Test Driven DevelopmentLinux Day 20091024 Test Driven Development
Linux Day 20091024 Test Driven Development
 
Test Driven Development for iOS
Test Driven Development for iOSTest Driven Development for iOS
Test Driven Development for iOS
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Vogliamo programmatori stupidi e pigri!
Vogliamo programmatori stupidi e pigri!Vogliamo programmatori stupidi e pigri!
Vogliamo programmatori stupidi e pigri!
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
TDD patterns and TDD strategies
TDD patterns and TDD strategiesTDD patterns and TDD strategies
TDD patterns and TDD strategies
 
Effective Code Transformations in C++
Effective Code Transformations in C++Effective Code Transformations in C++
Effective Code Transformations in C++
 
Testing
TestingTesting
Testing
 
Test Driven Development @ Xe.Net
Test Driven Development @ Xe.NetTest Driven Development @ Xe.Net
Test Driven Development @ Xe.Net
 
TypeScript, ovvero JavaScript che "non si rompe"
TypeScript, ovvero JavaScript che "non si rompe"TypeScript, ovvero JavaScript che "non si rompe"
TypeScript, ovvero JavaScript che "non si rompe"
 
Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
 
Workshop: Introduzione ad TDD
Workshop: Introduzione ad TDDWorkshop: Introduzione ad TDD
Workshop: Introduzione ad TDD
 
Java Unit Testing - Introduction
Java Unit Testing - IntroductionJava Unit Testing - Introduction
Java Unit Testing - Introduction
 
Creare Suite di Test Automatici intelligenti con Selenium IDE
Creare Suite di Test Automatici intelligenti con Selenium IDECreare Suite di Test Automatici intelligenti con Selenium IDE
Creare Suite di Test Automatici intelligenti con Selenium IDE
 
Ruby in 25 minuti
Ruby in 25 minutiRuby in 25 minuti
Ruby in 25 minuti
 
Mocking Objects Practices
Mocking Objects PracticesMocking Objects Practices
Mocking Objects Practices
 
LINQ, Entities Framework & ORMs
LINQ, Entities Framework & ORMsLINQ, Entities Framework & ORMs
LINQ, Entities Framework & ORMs
 
Algoritmi e Calcolo Parallelo 2012/2013 - Analisi degli Algoritmi
Algoritmi e Calcolo Parallelo 2012/2013 - Analisi degli AlgoritmiAlgoritmi e Calcolo Parallelo 2012/2013 - Analisi degli Algoritmi
Algoritmi e Calcolo Parallelo 2012/2013 - Analisi degli Algoritmi
 
Set Based Thinking
Set Based ThinkingSet Based Thinking
Set Based Thinking
 
Corso Programmazione Java Base
Corso Programmazione Java BaseCorso Programmazione Java Base
Corso Programmazione Java Base
 

Mais de Pietro Di Bello

Lessons learned in surviving to Technical Debt
Lessons learned in surviving to Technical DebtLessons learned in surviving to Technical Debt
Lessons learned in surviving to Technical DebtPietro Di Bello
 
Surviving to a Legacy Codebase - Codemotion Berlin 2018 Edition
Surviving to a Legacy Codebase - Codemotion Berlin 2018 EditionSurviving to a Legacy Codebase - Codemotion Berlin 2018 Edition
Surviving to a Legacy Codebase - Codemotion Berlin 2018 EditionPietro Di Bello
 
Surviving to a Legacy Codebase - Voxxed Days Ticino Edition
Surviving to a Legacy Codebase - Voxxed Days Ticino EditionSurviving to a Legacy Codebase - Voxxed Days Ticino Edition
Surviving to a Legacy Codebase - Voxxed Days Ticino EditionPietro Di Bello
 
Vivere per raccontarla: l’importanza del daily journal in un team agile
Vivere per raccontarla: l’importanza del daily journal in un team agileVivere per raccontarla: l’importanza del daily journal in un team agile
Vivere per raccontarla: l’importanza del daily journal in un team agilePietro Di Bello
 
Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...Pietro Di Bello
 
Continuous Delivery su progetti Java: cosa abbiamo imparato facendoci del male
Continuous Delivery su progetti Java: cosa abbiamo imparato facendoci del maleContinuous Delivery su progetti Java: cosa abbiamo imparato facendoci del male
Continuous Delivery su progetti Java: cosa abbiamo imparato facendoci del malePietro Di Bello
 
Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...Pietro Di Bello
 
Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...
Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...
Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...Pietro Di Bello
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012Pietro Di Bello
 
"Il dilettevole giuoco dell'oca" coding dojo
"Il dilettevole giuoco dell'oca" coding dojo"Il dilettevole giuoco dell'oca" coding dojo
"Il dilettevole giuoco dell'oca" coding dojoPietro Di Bello
 
Retrospective, StandUp Meeting e Daily Journal
Retrospective, StandUp Meeting e Daily JournalRetrospective, StandUp Meeting e Daily Journal
Retrospective, StandUp Meeting e Daily JournalPietro Di Bello
 

Mais de Pietro Di Bello (12)

Lessons learned in surviving to Technical Debt
Lessons learned in surviving to Technical DebtLessons learned in surviving to Technical Debt
Lessons learned in surviving to Technical Debt
 
Surviving to a Legacy Codebase - Codemotion Berlin 2018 Edition
Surviving to a Legacy Codebase - Codemotion Berlin 2018 EditionSurviving to a Legacy Codebase - Codemotion Berlin 2018 Edition
Surviving to a Legacy Codebase - Codemotion Berlin 2018 Edition
 
Surviving to a Legacy Codebase - Voxxed Days Ticino Edition
Surviving to a Legacy Codebase - Voxxed Days Ticino EditionSurviving to a Legacy Codebase - Voxxed Days Ticino Edition
Surviving to a Legacy Codebase - Voxxed Days Ticino Edition
 
Vivere per raccontarla: l’importanza del daily journal in un team agile
Vivere per raccontarla: l’importanza del daily journal in un team agileVivere per raccontarla: l’importanza del daily journal in un team agile
Vivere per raccontarla: l’importanza del daily journal in un team agile
 
Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...
 
Continuous Delivery su progetti Java: cosa abbiamo imparato facendoci del male
Continuous Delivery su progetti Java: cosa abbiamo imparato facendoci del maleContinuous Delivery su progetti Java: cosa abbiamo imparato facendoci del male
Continuous Delivery su progetti Java: cosa abbiamo imparato facendoci del male
 
Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...Hiring Great People: how we improved our recruiting process to build and grow...
Hiring Great People: how we improved our recruiting process to build and grow...
 
Scrum In A Nutshell
Scrum In A NutshellScrum In A Nutshell
Scrum In A Nutshell
 
Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...
Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...
Breaking the ice with agile - cinque strade per rompere il ghiaccio e introdu...
 
TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012TDD reloaded - JUGTAA 24 Ottobre 2012
TDD reloaded - JUGTAA 24 Ottobre 2012
 
"Il dilettevole giuoco dell'oca" coding dojo
"Il dilettevole giuoco dell'oca" coding dojo"Il dilettevole giuoco dell'oca" coding dojo
"Il dilettevole giuoco dell'oca" coding dojo
 
Retrospective, StandUp Meeting e Daily Journal
Retrospective, StandUp Meeting e Daily JournalRetrospective, StandUp Meeting e Daily Journal
Retrospective, StandUp Meeting e Daily Journal
 

A brief intro to TDD for a JUG-TAA event

  • 1. Test-Driven Development Coding Dojo Pietro Di Bello pietro.di.bello@xpeppers.com @pierodibello @xpeppers JUG Trentino Alto-Adige Agosto 2012
  • 2. Che cos’è il TDD? è una tecnica di design in cui lo sviluppo di una funzionalità è guidato dalla scrittura di uno o più unit test • si basa sull'uso di unit test • lo sviluppo del codice è guidato dalla scrittura di unit test che devono essere di volta in volta verificati • il test viene scritto ed eseguito PRIMA del codice stesso che consentirà di verificarlo
  • 3. Write a test public class AdderTest { @Test public void testTwoPlusThree() { Adder a = new Adder(); assertEquals(5, a.add(2, 3)); } }
  • 4. Now it compiles public class AdderTest { @Test public void testTwoPlusThree() { Adder a = new Adder(); assertEquals(5, a.add(2, 3)); } } public class Adder { public int add(int a, int b) { return 0; } }
  • 5. Red bar! public class AdderTest { @Test public void testTwoPlusThree() { Adder a = new Adder(); assertEquals(5, a.add(2, 3)); } } public class Adder { public int add(int a, int b) { return 0; } } Expected 5, was 0
  • 6. Do the simplest thing public class AdderTest { @Test public void testTwoPlusThree() { Adder a = new Adder(); assertEquals(5, a.add(2, 3)); } } public class Adder { public int add(int a, int b) { return 5; } }
  • 7. Refactor public class AdderTest { @Test public void testTwoPlusThree() { Adder a = new Adder(); assertEquals(5, a.add(2, 3)); } } public class Adder { public int add(int a, int b) { return a+b; } }
  • 8. The procedure 1. Write a test 2. Make it compile Expected 5, was 0 3. Make it pass quickly 4. Refactor to remove duplication
  • 9. Red Refactor Green Repeat every 2-10 min.
  • 10. Clean code that works.
  • 11. TDD: why? • Per abbattere la complessità • Consente di ridurre la soluzione di un problema complesso in tanti problemi più semplici (divide et impera)
  • 12. TDD: why? Ogni test rappresenta una opportunità di porre una domanda sul sistema, la cui risposta ci porterà ad un maggiore consolidamento della conoscenza e una riduzione dell'unknown
  • 13. TDD: why? When we write a test, we imagine the perfect interface for our operation.We are telling ourselves a story about how the operation will look from the outside. Our story won't always come true, but it's better to start from the best-possible application program interface (API) and work backward than to make things complicated, ugly, and "realistic" from the get-go. Kent Beck
  • 14. Simple design The code is simple enough when it: 0. Runs all the tests 1. Contains no duplication 2. Expresses every idea that we need to express 3. Has the minimum number of classes and functions (In this order) Kent Beck, Extreme Programming Explained
  • 15. Il primo test • deve essere piccolo • il più semplice possibile • ad es possiamo selezionare un caso degenere • tracciamo i primi contorni di una API ad un dettaglio molto più fine di quanto siamo abituati solitamente
  • 18. Il prossimo test Trattiamo ogni test come una nuova occasione per imparare e ridurre la complessità sul modello del problema Qual’è la prossima domanda a cui vogliamo rispondere?
  • 20. Uso della to-do list • Utile per gestire la complessità • elencare i diversi aspetti del problema • NON si elencano i test da implementare • non è TDD • Riduce lo stress • Bussola per farci capire a che punto siamo e non ci perdere la strada • Se mi viene in mente qualcosa la scrivo nella todolist e continuo sulla mia strada senza perdere focus • => tecnica del Pomodoro
  • 21.
  • 23. What’s a kata? A kata is meant to be memorized. Students of a kata study it as a form, not as a conclusion. It is not the conclusion of the kata that matters, it's the steps that lead to the conclusion. Bob Martin (http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata)
  • 24. The Bowling Game Kata By Robert Martin “Uncle Bob” http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata
  • 25. Il punteggio del bowling Ci sono 10 frame. In ogni frame il giocatore ha due possibilità di abbattere 10 birilli (pins). Il punteggio per il frame è il numero di birilli abbattuti, più i bonus per stike o spare. Uno spare è quando il giocatore abbatte 10 birilli in due tiri. Il bonus per quel frame è il numero di birilli abbattuti al tiro successivo. Nel frame 3 dell'esempio, il punteggio è 10 (i birilli abbattuti) più il bonus di 5 (abbattuti nel tiro successivo.) Uno strike è quando il giocatore abbatte tutti i birilli in un solo tiro. Il bonus per quel frame è il numero di birilli abbattuti nei due tiri successivi Nel decimo frame, se il giocatore fa uno strike o spare può fare i tiri necessari per completare il frame. In ogni caso, al decimo frame non vengono fatti più di tre tiri.
  • 26. I requisiti • Scrivete una classe“Game” con due metodi: • roll(pins : int) è chiamato ogni volta che il giocatore fa un tiro. L’argomento è il numero di birilli abbattuti. • score(): int è chiamato quando il gioco termina e ritorna il punteggio finale.
  • 27. Una veloce sessione di design Ovviamente avremo bisogno di una classe Game.
  • 28. Una veloce sessione di design Un gioco ha 10 frames.
  • 29. Una veloce sessione di design Un frame ha uno o due birilli (pins)
  • 30. Una veloce sessione di design Il decimo frame è diverso dagli altri: può avere due o tre tiri.
  • 31. Una veloce sessione di design La funzione score deve iterare su tutti i frames e calcolare i loro punteggi.
  • 32. Una veloce sessione di design Il punteggio di uno spare o di uno strike dipende dal punteggio del frame successivo
  • 33. Coding Katas: String Calculator by Roy Osherove (http://osherove.com/tdd- kata-1)
  • 34. StringCalculator Kata Create a simple String calculator with a method int Add(string numbers) The method can take zero, one or two numbers, and will return their sum • for example “” or “1” or “1,2” • for an empty string it will return 0 Start with the simplest test case of an empty string and move to one and two numbers
  • 35. StringCalculator Kata Remember to solve things as simply as possible so that you force yourself to write tests you did not think about Remember to refactor after each passing test
  • 36. StringCalculator Kata Allow the Add method to handle an unknown amount of numbers
  • 37. StringCalculator Kata Allow the Add method to handle new lines between numbers (instead of commas). • the following input is ok:  “1n2,3”  (will equal 6) • the following input is NOT ok:  “1,n” (not need to prove it - just clarifying)
  • 38. StringCalculator Kata Support different delimiters to change a delimiter, the beginning of the string will contain a separate line that looks like this: “//[delimiter]n[numbers…]” for example “//;n1;2” should return three where the default delimiter is ‘;’ . the first line is optional. all existing scenarios should still be supported
  • 39. StringCalculator Kata Calling Add with a negative number will throw an exception “negatives not allowed” - and the negative that was passed. If there are multiple negatives, show all of them in the exception message
  • 40. StringCalculator Kata Numbers bigger than 1000 should be ignored, so adding 2 + 1001 = 2
  • 41. More on code kata • http://codekata.pragprog.com/ • http://codingdojo.org/ • https://sites.google.com/site/tddproblems/all-problems-1 • http://xp123.com/articles/tests-from-a-hat/
  • 42. Homework Roman Numerals kata: write a Roman class which converts an integer into a roman number string. es: 12 => “XII” Bonus: can you write the inverse converter (from roman to integer)? es: “IX” => 9
  • 43. Homework Prime Factors kata: • http://butunclebob.com/ ArticleS.UncleBob.ThePrimeFactorsKata
  • 44. Supermarket checkout • Compute the total price • Scan items one at a time • In any order
  • 45. Copyright 2008-2012 XPeppers Tutti i diritti di riproduzione sono riservati.

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. Quickly add a test.\nRun all tests and see the new one fail.\nMake a little change.\nRun all tests and see them all succeed.\nRefactor to remove duplication.\n\n
  9. \n
  10. First we'll solve the “that works” part\n Then we'll solve the “clean code” part\n
  11. \n
  12. \n
  13. \n
  14. \n
  15. Esempio:\n \n Roman 0 => ""\n \n Mercato Titoli\n il mercato è chiuso di default\n non ci sono ordini su un titolo che non esiste\n se metto ordini su un titolo con il mercato chiuso ho una eccezione\n\n
  16. \n
  17. \n
  18. Il prossimo test\n Trattiamo ogni test come una nuova occasione per imparare e ridurre la complessità sul modello del problema \n ogni test ci da ulteriore conoscenza\n ES\n Mercato Titoli\n qual'è la prossima domanda a cui vogliamo rispondere?\n\n
  19. Il prossimo test\n Trattiamo ogni test come una nuova occasione per imparare e ridurre la complessità sul modello del problema \n ogni test ci da ulteriore conoscenza\n ES\n Mercato Titoli\n qual'è la prossima domanda a cui vogliamo rispondere?\n\n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n