SlideShare a Scribd company logo
1 of 51
Download to read offline
Take pride in your code
Test-Driven Development
Credits
Ahmed HammadAmeer Gaafar
Disclaimer: The content and structure of this slides is based on the presentation Ameer and Ahmed authored.
Introductions first!
● I am
⚪ Ahmed Moawad
⚪ CSD 2009
⚪ Software Engineer
⚪ Chief Operating Officer at BADR
⚪ @ ahmed.moawad@badrit.com
⚪ in /ahmedmoawadibraheem
● Who are you?!
Expectations?
What do you think this, considerably long, session is
about?!
So, it’s not about:
● Test first.
● Unit testing.
● Testing!
Surprisingly, it’s about
design :D
Logistics
● 50 minutes sprints, 10 minutes break.
● Be on time.
● Cell phones SILENT.
● Feel free to:
⚪ Speak up.
⚪ Discuss.
⚪ Sit in groups, form teams.
⚪ Mingle, move around, go out and come back (but QUIETLY)
Why even bother?
Self-Testing Code
Traditionally
● How much do you code before your test?
● How do you test?
● How do you find bugs?
Code Compile Test
Fix bugs
The debugger curve (uncle Bob’s* claim!)
Debugging Skills
Productivity
* Robert Martin
Testing Code, with code!
Move coding into an emotional state!
Take pride!
Love what you do!
Have fun!
A typical example
public class TestCalculator {
public static void main(String[] args) {
Calculator c = new Calculator();
double result = c.add(5, 6);
if(result != 11) {
System.out.println(“wrong result”);
}
// rest of the class omitted
}
}
public class Calculator {
public double add(double a, double b) {
return a + b;
}
public double sub(double a, double b) {
return a - b;
}
public double mul(double a, double b) {
return a * b;
}
public double div(double a, double b) {
return a / b;
}
}
Production Code
(System Under
Test)
Test Code
Self-Testing Code
Write Code Compile
Write Test
Code
Make tests pass
Run Tests
Compile
Test Code
Self-Testing Code
By the programmers, for the programmers
Programmers take responsibility of quality
Impact on Code
● Smaller pieces
● Separation of concerns
● Easier to test
● Easier to modify
Regression testing becomes
almost free!
Loose coupling
Iff you use good names
Solid system (not fragile)
More benefits of tests
● Documentation of code.
⚪ Living, executable documentation.
● Catch future defects.
⚪ You have a safety net.
● Long-term time saving.
⚪ You know when something is broken before deployment.
But testing is merely a tool, it not the process.
Now what?
What do you think will/should happen
to the test code?
xUnit Family
● Frameworks for writing programmer tests
● Integrated with IDEs and build environments
● Exist for virtually all programming languages and
environments
It’s not about units, it’s about
self-testing code
How everything started
Writing tests with JUnit
import . . . // imports omitted
public class TestCalculator {
public static void main(String[] args) {
Calculator c = new Calculator();
double result = c.add(5, 6);
if(result != 11) {
System.out.println(“wrong result”);
}
// rest of the class if omitted
}
}
import . . . // different imports, omitted
public class TestCalculator {
@Test
public void addTwoNumbers_ReturnsSum() {
Calculator c = new Calculator();
double result = c.add(5, 6);
assertEquals(21, result);
}
}
What it looks like in real life :)
Test cases Coverage
Success
Production code
Test code
Environment Setup Exercise
Enough talking, let’s power up those machines
Temperature conversion
℃ × 9/5 + 32 = ℉
(℉ - 32) × 5/9 = ℃
Tennis Score Exercise
Tennis Scoring System
Player 1 Player 2 Score
⬤ Fifteen - Love
⬤ ⬤ Fifteen - Fifteen
⬤⬤ ⬤ Thirty - Fifteen
⬤⬤⬤ ⬤ Forty - Fifteen
⬤⬤⬤⬤ ⬤ Game, Player 1
⬤⬤ ⬤⬤⬤ Thirty - Forty
⬤⬤⬤ ⬤⬤⬤ Deuce
⬤⬤⬤⬤ ⬤⬤⬤ Advantage, Player 1
⬤⬤⬤⬤ ⬤⬤⬤⬤ Deuce
⬤⬤⬤⬤ ⬤⬤⬤⬤⬤ Advantage, Player 2
⬤⬤⬤⬤ ⬤⬤⬤⬤⬤⬤ Game, Player 2
Benefits of self-testing code?
● Executable proof of quality
● Free regression test
● Inspires confidence
● Reduces cost of change
Bonus :D
A formal proof! It doesn’t get
more formal than that!!
Added cost to development time is about
50%, BUT, it’s worth the investment
“Never in the field of
software development
have so many owed so
much to so few lines of
code.”
Martin Fowler
Discussion
● So, what is the ‘unit’ in xunit?
⚪ Class?
⚪ Method?
⚪ Component?
Interesting behavior
There ought to be some boring stuff
here about SUT, DOC and Isolation!
System Under Test Depended-on Object
Leap Year Exercise
boolean leapYear(int year)
A leap year is defined as one that is divisible by 4, unless
it’s divisible by a 100, in which case, it should also be
divisible by 400.
Lear Years: 1996, 2000
Common Year: 2001, 1900
Test-Driven Development
Yes, up to this point, we didn’t speak off TDD yet :D
Traditionally
Code Compile Test
Fix bugs
Write Code Compile
Write Test
Code
Make tests pass
Run Tests
Compile
Test Code
TDD
Write a
test
See it fail
Make it
pass
Make it
better
Establish
expectations
Single test
Failure is
progress
Using the simplest
solution, even if ugly
Now improve the design
guarded with tests and
better understanding
Refactor
Now, to the 1st live TDD
session
The Bowling Kata
... but before we dig in
Red (test)
Green (make it pass)
Refactor
The Bowling Kata
● 10 frames per game, up to 2 attempts per frame
● All pins down from 1st attempt (strike)
⚪ Frame is over, Score is 10 + score the next two balls
● All pins down in the two balls of the frame (spare)
⚪ Score is 10 + score if the next ball
● Less than 10 down in two balls of the frame
⚪ Score is number of pins down
● Spare in the 10th frame?
⚪ One bonus ball
● Strike in the 10th frame?
⚪ Two bonus balls
Bowling score calculator design
+ rolls(pins : int)
+ score(): int
Game
+ score(): int
Frame
- pins: int
Roll
Tenth Frame
10 1..2
1
Next frame
INITIAL DESIGN
The Bowling Kata
So, how did you find it?
TDD Benefits
All testing benefits
+
● Consumer focused, simple design
● Just enough code to meet expectations (lean)
● No untested code
Now, it’s your turn
Your first TDD program
Standard deviation
Write a program that prints the standard deviation of the
a series of a population of numbers.
... but before you dig in!
Remember
● You’re learning a technique, not solving a problem
● Baby steps
● Failing tests first
● Just enough code to pass the test
● Keep it clean
FizzBuzz Kata
Write a program that prints the numbers from 1 to 100,
BUT:
● For multiples of three, print “Fizz”
● For multiples of five, print “Buzz”
● For multiples of both, print “FizzBuzz”
Roman Numerals Kata
Convert Arabic numbers to Roman:
1 -> I
2 -> II
3 -> III
4 -> IV
5 -> V
6 -> VI
7 -> VII
8 -> VIII
9 -> IX
10 -> X
20 -> XX
30 -> XXX
40 -> XL
50 -> L
60 -> LX
70 -> LXX
80 -> LXXX
90 -> XC
1000 -> M
2000 -> MM
3000 -> MMM
100 -> C
200 -> CC
300 -> CCC
400 -> CD
500 -> D
600 -> DC
700 -> DCC
800 -> DCCC
900 -> CM
1990 = MCMXC 99 = XCIX
2008 = MMVIII 47 = XLVII
Prime Factors Kata
Print the prime factors of an arbitrary number
1 -> { }
2 -> { 2 }
6 -> { 2, 3 }
12 -> { 2, 2, 3 }
14 -> { 2, 7 }
286 -> { 2, 11, 13 }
Test smells
● Obscure test
● Conditional test
● Hard-to-test code
● Test code duplication
● Test logic in production
● Assertion roulette
● Erratic test
● Fragile test
● Frequent debugging
● Manual intervention
● Slow test
Code Smells Behavior Smells
Unit testing Sweet Spot
● Fast executing.
● Independent.
● Large number.
● Narrow in focus.
● Simple in structure.
● Easy to setup and teardown.
Further considerations
● Different test runners (Jasmine default, Karma, ...)
⚪ Why?
● Impact on development time.
⚪ Usually, people would tell you it’s a 50% tax.
⚪ Usually, it’s not true :D.
● Code coverage.
● Data providers.
● Mocks and stubs.
Conclusion
● Simple != Easy.
● You have to master
the craft to reap the
fruit.
● The art of fearless
programming.
● Programming, enjoyable
again.
● The dream of executable
requirements.
● Towards a better design
for software.
● A hope for the lost souls.
Other possible titles!
All code is guilty until
proven innocent
All code is legacy unless it
has tests
Thank you!
I hope you enjoyed this class

More Related Content

Viewers also liked

Bus 475 capstone final examination part 2 new 2016
Bus 475 capstone final examination part 2 new 2016Bus 475 capstone final examination part 2 new 2016
Bus 475 capstone final examination part 2 new 2016sergejsvolkovs10
 
Presentación 3 Proyecto de Seminario de Informatica
Presentación 3 Proyecto de Seminario de InformaticaPresentación 3 Proyecto de Seminario de Informatica
Presentación 3 Proyecto de Seminario de Informaticaana0711446
 
Formato de sesiion de aprendizaje reyes elva
Formato de sesiion de aprendizaje reyes elvaFormato de sesiion de aprendizaje reyes elva
Formato de sesiion de aprendizaje reyes elvaElva Reyes
 
Réveil en Form' 14 - IRL
Réveil en Form' 14 - IRLRéveil en Form' 14 - IRL
Réveil en Form' 14 - IRLAlain Krafft
 
Los valores1
Los valores1Los valores1
Los valores1peterbrus
 
προληπτικη παιδοφθαλμολογια
προληπτικη παιδοφθαλμολογιαπροληπτικη παιδοφθαλμολογια
προληπτικη παιδοφθαλμολογιαStavros Liloglou
 

Viewers also liked (12)

Bus 475 capstone final examination part 2 new 2016
Bus 475 capstone final examination part 2 new 2016Bus 475 capstone final examination part 2 new 2016
Bus 475 capstone final examination part 2 new 2016
 
Project slides
Project slidesProject slides
Project slides
 
Anicetto gracias!!!
Anicetto gracias!!!Anicetto gracias!!!
Anicetto gracias!!!
 
Presentación 3 Proyecto de Seminario de Informatica
Presentación 3 Proyecto de Seminario de InformaticaPresentación 3 Proyecto de Seminario de Informatica
Presentación 3 Proyecto de Seminario de Informatica
 
Formato de sesiion de aprendizaje reyes elva
Formato de sesiion de aprendizaje reyes elvaFormato de sesiion de aprendizaje reyes elva
Formato de sesiion de aprendizaje reyes elva
 
Nishant_Resume-3_1_
Nishant_Resume-3_1_Nishant_Resume-3_1_
Nishant_Resume-3_1_
 
Presentation
PresentationPresentation
Presentation
 
Réveil en Form' 14 - IRL
Réveil en Form' 14 - IRLRéveil en Form' 14 - IRL
Réveil en Form' 14 - IRL
 
038_Esquire_03_2015
038_Esquire_03_2015038_Esquire_03_2015
038_Esquire_03_2015
 
Syllabus 2016 dec-20
Syllabus 2016 dec-20Syllabus 2016 dec-20
Syllabus 2016 dec-20
 
Los valores1
Los valores1Los valores1
Los valores1
 
προληπτικη παιδοφθαλμολογια
προληπτικη παιδοφθαλμολογιαπροληπτικη παιδοφθαλμολογια
προληπτικη παιδοφθαλμολογια
 

Similar to Take Pride in Your Code - Test-Driven Development

TDD: seriously, try it! 
TDD: seriously, try it! TDD: seriously, try it! 
TDD: seriously, try it! Nacho Cougil
 
How to quickly add a safety net to a legacy codebase
How to quickly add a safety net to a legacy codebaseHow to quickly add a safety net to a legacy codebase
How to quickly add a safety net to a legacy codebaseNelis Boucké
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testingdn
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testingmalcolmt
 
Day1 - TDD (Lecture SS 2015)
Day1 - TDD (Lecture SS 2015)Day1 - TDD (Lecture SS 2015)
Day1 - TDD (Lecture SS 2015)wolframkriesing
 
Keynote AST 2016
Keynote AST 2016Keynote AST 2016
Keynote AST 2016Kim Herzig
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017Xavi Hidalgo
 
Deliberate Practice, New Learning Styles (2015)
Deliberate Practice, New Learning Styles (2015)Deliberate Practice, New Learning Styles (2015)
Deliberate Practice, New Learning Styles (2015)Peter Kofler
 
Coding Dojo: String Calculator (2013)
Coding Dojo: String Calculator (2013)Coding Dojo: String Calculator (2013)
Coding Dojo: String Calculator (2013)Peter Kofler
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019Paulo Clavijo
 
Introduction to Continuous Delivery
Introduction to Continuous DeliveryIntroduction to Continuous Delivery
Introduction to Continuous DeliveryGiovanni Toraldo
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentjakubkoci
 
Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Danny Preussler
 
Test driven development_continuous_integration
Test driven development_continuous_integrationTest driven development_continuous_integration
Test driven development_continuous_integrationhaochenglee
 
Deliberate Practice (Agile Slovenia 2015)
Deliberate Practice (Agile Slovenia 2015)Deliberate Practice (Agile Slovenia 2015)
Deliberate Practice (Agile Slovenia 2015)Peter Kofler
 
Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5rtpaem
 
Test Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEMTest Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEMSagar Sane
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptxTomas561914
 

Similar to Take Pride in Your Code - Test-Driven Development (20)

TDD: seriously, try it! 
TDD: seriously, try it! TDD: seriously, try it! 
TDD: seriously, try it! 
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
How to quickly add a safety net to a legacy codebase
How to quickly add a safety net to a legacy codebaseHow to quickly add a safety net to a legacy codebase
How to quickly add a safety net to a legacy codebase
 
Behaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About TestingBehaviour Driven Development and Thinking About Testing
Behaviour Driven Development and Thinking About Testing
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testing
 
Day1 - TDD (Lecture SS 2015)
Day1 - TDD (Lecture SS 2015)Day1 - TDD (Lecture SS 2015)
Day1 - TDD (Lecture SS 2015)
 
Keynote AST 2016
Keynote AST 2016Keynote AST 2016
Keynote AST 2016
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017
 
Deliberate Practice, New Learning Styles (2015)
Deliberate Practice, New Learning Styles (2015)Deliberate Practice, New Learning Styles (2015)
Deliberate Practice, New Learning Styles (2015)
 
Coding Dojo: String Calculator (2013)
Coding Dojo: String Calculator (2013)Coding Dojo: String Calculator (2013)
Coding Dojo: String Calculator (2013)
 
TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019TDD and Simple Design Workshop - Session 1 - March 2019
TDD and Simple Design Workshop - Session 1 - March 2019
 
Introduction to Continuous Delivery
Introduction to Continuous DeliveryIntroduction to Continuous Delivery
Introduction to Continuous Delivery
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)
 
Test driven development_continuous_integration
Test driven development_continuous_integrationTest driven development_continuous_integration
Test driven development_continuous_integration
 
Deliberate Practice (Agile Slovenia 2015)
Deliberate Practice (Agile Slovenia 2015)Deliberate Practice (Agile Slovenia 2015)
Deliberate Practice (Agile Slovenia 2015)
 
Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5Test Driven Development in AEM/CQ5
Test Driven Development in AEM/CQ5
 
Test Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEMTest Driven Development in CQ5/AEM
Test Driven Development in CQ5/AEM
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Test-Driven Development.pptx
Test-Driven Development.pptxTest-Driven Development.pptx
Test-Driven Development.pptx
 

More from BADR

Sunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrSunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrBADR
 
Docker up and Running For Web Developers
Docker up and Running For Web DevelopersDocker up and Running For Web Developers
Docker up and Running For Web DevelopersBADR
 
Vue.js
Vue.jsVue.js
Vue.jsBADR
 
There and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesThere and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesBADR
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility PrincipleBADR
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL DatabasesBADR
 
Explicit Semantic Analysis
Explicit Semantic AnalysisExplicit Semantic Analysis
Explicit Semantic AnalysisBADR
 
Getting some Git
Getting some GitGetting some Git
Getting some GitBADR
 
ReactiveX
ReactiveXReactiveX
ReactiveXBADR
 
Algorithms - A Sneak Peek
Algorithms - A Sneak PeekAlgorithms - A Sneak Peek
Algorithms - A Sneak PeekBADR
 
Android from A to Z
Android from A to ZAndroid from A to Z
Android from A to ZBADR
 
Apache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringApache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringBADR
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL IndexingBADR
 
Duckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternDuckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternBADR
 
The Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternThe Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternBADR
 

More from BADR (15)

Sunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrSunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into Solr
 
Docker up and Running For Web Developers
Docker up and Running For Web DevelopersDocker up and Running For Web Developers
Docker up and Running For Web Developers
 
Vue.js
Vue.jsVue.js
Vue.js
 
There and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesThere and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming Languages
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL Databases
 
Explicit Semantic Analysis
Explicit Semantic AnalysisExplicit Semantic Analysis
Explicit Semantic Analysis
 
Getting some Git
Getting some GitGetting some Git
Getting some Git
 
ReactiveX
ReactiveXReactiveX
ReactiveX
 
Algorithms - A Sneak Peek
Algorithms - A Sneak PeekAlgorithms - A Sneak Peek
Algorithms - A Sneak Peek
 
Android from A to Z
Android from A to ZAndroid from A to Z
Android from A to Z
 
Apache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringApache Hadoop - Big Data Engineering
Apache Hadoop - Big Data Engineering
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL Indexing
 
Duckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternDuckville - The Strategy Design Pattern
Duckville - The Strategy Design Pattern
 
The Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design PatternThe Perks and Perils of the Singleton Design Pattern
The Perks and Perils of the Singleton Design Pattern
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 

Take Pride in Your Code - Test-Driven Development

  • 1.
  • 2. Take pride in your code Test-Driven Development
  • 3. Credits Ahmed HammadAmeer Gaafar Disclaimer: The content and structure of this slides is based on the presentation Ameer and Ahmed authored.
  • 4. Introductions first! ● I am ⚪ Ahmed Moawad ⚪ CSD 2009 ⚪ Software Engineer ⚪ Chief Operating Officer at BADR ⚪ @ ahmed.moawad@badrit.com ⚪ in /ahmedmoawadibraheem ● Who are you?!
  • 5. Expectations? What do you think this, considerably long, session is about?!
  • 6. So, it’s not about: ● Test first. ● Unit testing. ● Testing! Surprisingly, it’s about design :D
  • 7. Logistics ● 50 minutes sprints, 10 minutes break. ● Be on time. ● Cell phones SILENT. ● Feel free to: ⚪ Speak up. ⚪ Discuss. ⚪ Sit in groups, form teams. ⚪ Mingle, move around, go out and come back (but QUIETLY)
  • 10. Traditionally ● How much do you code before your test? ● How do you test? ● How do you find bugs? Code Compile Test Fix bugs
  • 11. The debugger curve (uncle Bob’s* claim!) Debugging Skills Productivity * Robert Martin
  • 12. Testing Code, with code! Move coding into an emotional state! Take pride! Love what you do! Have fun!
  • 13. A typical example public class TestCalculator { public static void main(String[] args) { Calculator c = new Calculator(); double result = c.add(5, 6); if(result != 11) { System.out.println(“wrong result”); } // rest of the class omitted } } public class Calculator { public double add(double a, double b) { return a + b; } public double sub(double a, double b) { return a - b; } public double mul(double a, double b) { return a * b; } public double div(double a, double b) { return a / b; } } Production Code (System Under Test) Test Code
  • 14. Self-Testing Code Write Code Compile Write Test Code Make tests pass Run Tests Compile Test Code
  • 15. Self-Testing Code By the programmers, for the programmers Programmers take responsibility of quality
  • 16. Impact on Code ● Smaller pieces ● Separation of concerns ● Easier to test ● Easier to modify Regression testing becomes almost free! Loose coupling Iff you use good names Solid system (not fragile)
  • 17. More benefits of tests ● Documentation of code. ⚪ Living, executable documentation. ● Catch future defects. ⚪ You have a safety net. ● Long-term time saving. ⚪ You know when something is broken before deployment. But testing is merely a tool, it not the process.
  • 18. Now what? What do you think will/should happen to the test code?
  • 19. xUnit Family ● Frameworks for writing programmer tests ● Integrated with IDEs and build environments ● Exist for virtually all programming languages and environments It’s not about units, it’s about self-testing code
  • 21. Writing tests with JUnit import . . . // imports omitted public class TestCalculator { public static void main(String[] args) { Calculator c = new Calculator(); double result = c.add(5, 6); if(result != 11) { System.out.println(“wrong result”); } // rest of the class if omitted } } import . . . // different imports, omitted public class TestCalculator { @Test public void addTwoNumbers_ReturnsSum() { Calculator c = new Calculator(); double result = c.add(5, 6); assertEquals(21, result); } }
  • 22. What it looks like in real life :) Test cases Coverage Success Production code Test code
  • 23. Environment Setup Exercise Enough talking, let’s power up those machines
  • 24. Temperature conversion ℃ × 9/5 + 32 = ℉ (℉ - 32) × 5/9 = ℃
  • 26. Tennis Scoring System Player 1 Player 2 Score ⬤ Fifteen - Love ⬤ ⬤ Fifteen - Fifteen ⬤⬤ ⬤ Thirty - Fifteen ⬤⬤⬤ ⬤ Forty - Fifteen ⬤⬤⬤⬤ ⬤ Game, Player 1 ⬤⬤ ⬤⬤⬤ Thirty - Forty ⬤⬤⬤ ⬤⬤⬤ Deuce ⬤⬤⬤⬤ ⬤⬤⬤ Advantage, Player 1 ⬤⬤⬤⬤ ⬤⬤⬤⬤ Deuce ⬤⬤⬤⬤ ⬤⬤⬤⬤⬤ Advantage, Player 2 ⬤⬤⬤⬤ ⬤⬤⬤⬤⬤⬤ Game, Player 2
  • 27. Benefits of self-testing code? ● Executable proof of quality ● Free regression test ● Inspires confidence ● Reduces cost of change Bonus :D A formal proof! It doesn’t get more formal than that!! Added cost to development time is about 50%, BUT, it’s worth the investment
  • 28. “Never in the field of software development have so many owed so much to so few lines of code.” Martin Fowler
  • 29. Discussion ● So, what is the ‘unit’ in xunit? ⚪ Class? ⚪ Method? ⚪ Component? Interesting behavior
  • 30. There ought to be some boring stuff here about SUT, DOC and Isolation! System Under Test Depended-on Object
  • 31. Leap Year Exercise boolean leapYear(int year) A leap year is defined as one that is divisible by 4, unless it’s divisible by a 100, in which case, it should also be divisible by 400. Lear Years: 1996, 2000 Common Year: 2001, 1900
  • 32. Test-Driven Development Yes, up to this point, we didn’t speak off TDD yet :D
  • 33. Traditionally Code Compile Test Fix bugs Write Code Compile Write Test Code Make tests pass Run Tests Compile Test Code
  • 34. TDD Write a test See it fail Make it pass Make it better Establish expectations Single test Failure is progress Using the simplest solution, even if ugly Now improve the design guarded with tests and better understanding Refactor
  • 35. Now, to the 1st live TDD session The Bowling Kata
  • 36. ... but before we dig in Red (test) Green (make it pass) Refactor
  • 37. The Bowling Kata ● 10 frames per game, up to 2 attempts per frame ● All pins down from 1st attempt (strike) ⚪ Frame is over, Score is 10 + score the next two balls ● All pins down in the two balls of the frame (spare) ⚪ Score is 10 + score if the next ball ● Less than 10 down in two balls of the frame ⚪ Score is number of pins down ● Spare in the 10th frame? ⚪ One bonus ball ● Strike in the 10th frame? ⚪ Two bonus balls
  • 38. Bowling score calculator design + rolls(pins : int) + score(): int Game + score(): int Frame - pins: int Roll Tenth Frame 10 1..2 1 Next frame INITIAL DESIGN
  • 39. The Bowling Kata So, how did you find it?
  • 40. TDD Benefits All testing benefits + ● Consumer focused, simple design ● Just enough code to meet expectations (lean) ● No untested code
  • 41. Now, it’s your turn Your first TDD program
  • 42. Standard deviation Write a program that prints the standard deviation of the a series of a population of numbers.
  • 43. ... but before you dig in! Remember ● You’re learning a technique, not solving a problem ● Baby steps ● Failing tests first ● Just enough code to pass the test ● Keep it clean
  • 44. FizzBuzz Kata Write a program that prints the numbers from 1 to 100, BUT: ● For multiples of three, print “Fizz” ● For multiples of five, print “Buzz” ● For multiples of both, print “FizzBuzz”
  • 45. Roman Numerals Kata Convert Arabic numbers to Roman: 1 -> I 2 -> II 3 -> III 4 -> IV 5 -> V 6 -> VI 7 -> VII 8 -> VIII 9 -> IX 10 -> X 20 -> XX 30 -> XXX 40 -> XL 50 -> L 60 -> LX 70 -> LXX 80 -> LXXX 90 -> XC 1000 -> M 2000 -> MM 3000 -> MMM 100 -> C 200 -> CC 300 -> CCC 400 -> CD 500 -> D 600 -> DC 700 -> DCC 800 -> DCCC 900 -> CM 1990 = MCMXC 99 = XCIX 2008 = MMVIII 47 = XLVII
  • 46. Prime Factors Kata Print the prime factors of an arbitrary number 1 -> { } 2 -> { 2 } 6 -> { 2, 3 } 12 -> { 2, 2, 3 } 14 -> { 2, 7 } 286 -> { 2, 11, 13 }
  • 47. Test smells ● Obscure test ● Conditional test ● Hard-to-test code ● Test code duplication ● Test logic in production ● Assertion roulette ● Erratic test ● Fragile test ● Frequent debugging ● Manual intervention ● Slow test Code Smells Behavior Smells
  • 48. Unit testing Sweet Spot ● Fast executing. ● Independent. ● Large number. ● Narrow in focus. ● Simple in structure. ● Easy to setup and teardown.
  • 49. Further considerations ● Different test runners (Jasmine default, Karma, ...) ⚪ Why? ● Impact on development time. ⚪ Usually, people would tell you it’s a 50% tax. ⚪ Usually, it’s not true :D. ● Code coverage. ● Data providers. ● Mocks and stubs.
  • 50. Conclusion ● Simple != Easy. ● You have to master the craft to reap the fruit. ● The art of fearless programming. ● Programming, enjoyable again. ● The dream of executable requirements. ● Towards a better design for software. ● A hope for the lost souls. Other possible titles! All code is guilty until proven innocent All code is legacy unless it has tests
  • 51. Thank you! I hope you enjoyed this class