SlideShare a Scribd company logo
TDD Walkthrough
Library Fine
Peter Kha: peter.kha@greatersum.com
TDD Walkthrough - Library Fine
Hello and welcome to my TDD Walkthrough!
Today’s exercise is Library Fine, taken from
HackerRank.com at the following URL:
https://www.hackerrank.com/challenges/library-fi
ne/problem
TDD Walkthrough - Library Fine
In these TDD Walkthroughs, I assume that my
readers have basic knowledge of test driven
development. I highly suggest having an
understanding of TDD before going through this
walkthrough. The following blog post explains
the cycles of TDD.
http://blog.cleancoder.com/uncle-bob/2014/12/1
7/TheCyclesOfTDD.html
I also assume that my readers have knowledge
of refactoring tools and terminology. If you need
more information, this blog post on the six core
refactorings will provide enough information.
http://arlobelshee.com/the-core-6-refactorings/
TDD Walkthrough - Library Fine
For this exercise, I have the following already set up:
Chrome browser
Visual Studio Code or your personal IDE
Jasmine testing framework
(see my other blog on setting up: https://www.greatersum.com/tdd-setup-jasmine/)
With the above already set up, let’s get started!
TDD Walkthrough - Library Fine
This walkthrough starts with an already set up
Jasmine standalone project from my other blog
post.
From there, I will create the file that contains my
tests.
TDD Walkthrough - Library Fine
There are various conventions for file names out
there. I tend to use the affectionately dubbed
kabob-case: library-fine.spec.js
TDD Walkthrough - Library Fine
This is a spec file. This file needs to be included
in the Jasmine spec runner, so open up the
SpecRunner.html file next.
Look for the comment that says “include spec
files here”, and include the spec file you just
created.
TDD Walkthrough - Library Fine
We are now ready to write tests. Which tests do
we write? Let’s start a test list.
The first rule of Library Fine talks about books
returned on or before the due date. What kinds
of tests can come from this? I can think of 2.
First, the book is returned today Jan 08, 2018
and it is due tomorrow Jan 09, 2018. It is
returned before the due date, so no fee is due.
Second, the book is returned today Jan 08,
2018 and it is due today Jan 08, 2018. It is
returned on the due date, and no fee is due.
Returned 01/08/2018
Due 01/09/2018
No Fee Due
Returned 01/08/2018
Due 01/08/2018
No Fee Due
TDD Walkthrough - Library Fine
For the second rule, let’s say a book is returned
Jan 08, 2018 and it was due Jan 07, 2018. It is
one day late, which means 15 Hackos are due.
For the third rule, let’s say a book is returned
Feb 08, 2018 and it was due Jan 08, 2018. It
was due the previous month, which means 500
Hackos are due.
For the last rule, we’ll say a book was returned
Jan 01, 2019 and it was due Jan 08, 2018. It
was returned after the calendar year it was due
and thus 10000 Hackos are due.
Returned 01/08/2018
Due 01/07/2018
15 Hackos Due
Returned 02/08/2018
Due 01/08/2018
500 Hackos Due
Returned 01/01/2019
Due 01/08/2018
10000 Hackos Due
TDD Walkthrough - Library Fine
This test list looks like it covers all the rules for the Library Fine exercise. We have enough to get started.
Returned 01/08/2018, Due 01/09/2018, No Fee Due
Returned 01/08/2018, Due 01/08/2018, No Fee Due
Returned 01/08/2018, Due 01/07/2018, 15 Hackos Due
Returned 02/08/2018, Due 01/08/2018, 500 Hackos Due
Returned 01/01/2019, Due 01/08/2018, 10000 Hackos Due
TDD Walkthrough - Library Fine
Let’s write our first test. First, we create the test
suite:
And then we write the test function:
In our test function, we write what we are
expecting:
TDD Walkthrough - Library Fine
At this point, you should be able to run your test runner HTML file by opening it in
the browser, and see a failing test.
Failing the test here is good! You haven’t written any production code yet, and
that’s ok. What you did write is a test that will tell you when your code fulfilled a
purpose, and that is to return a fee of 0 when the book returned before the due
date. It’s not much, but we take one step at a time.
TDD Walkthrough - Library Fine
Ok, so what does the test runner say?
libraryFine is not defined. That makes sense, we
haven’t written anything called libraryFine yet.
Let’s go make that function!
TDD Walkthrough - Library Fine
To keep the code organized well, the tests are
contained in the spec file, in the spec folder.
So then our source code should go in the source
folder!
TDD Walkthrough - Library Fine
Our new source file will need to be included in
the Spec Runner though, so let’s not forget to do
that.
TDD Walkthrough - Library Fine
Now back to our source file. The first issue is
that theTimeInWords is not defined, so let’s go
define it.
TDD Walkthrough - Library Fine
You might be tempted to go implement all of the function right now. But bear with
me and take one small step at a time. Let’s focus on the error at hand, and we’ll
tackle each issue as they come up. That way we don’t write extra code for no
reason.
This is, after all, development that is driven by testing. So run the tests again. You
can rerun the tests by refreshing the spec runner page.
TDD Walkthrough - Library Fine
Ok, different error message. Expected
undefined to be 0.
Well, the solution sounds simple. Make our
function return 0!
TDD Walkthrough - Library Fine
This solution will make you cringe. It makes me cringe.
But you never write more code than you need. That prevents you from wasting
time on extra code, and it prevents you from writing code that can break other
things in other ways.
Focus on minimal design, and drive your code towards the functionality you want
with tests.
TDD Walkthrough - Library Fine
Ok, that being said, our current test should pass.
And it does! Good, we move on to the next test
on our list.
TDD Walkthrough - Library Fine
With the first test case done, let’s do the second
case: book returned and due on Jan 08, 2018.
Run the tests, and it appears we’re already
passing? Wait, that’s unexpected. If we were
following the TDD cycle, our new test should be
failing.
TDD Walkthrough - Library Fine
This second test was already passing because what we did for the first test fulfilled
the second test. This means our second test doesn’t add anything new to
production code. How useful is our second test then?
It is normal during TDD to change your test list as you discover new things. Your
test list is not perfect. It is a work in progress, and that is okay.
So what do we do with this already passing test? People have different
approaches. You can take it out. You can keep it there. If the situation fits, you can
also put it together with another test.
TDD Walkthrough - Library Fine
I will combine the second test with the first test.
The reasoning here is that the return from the
function is expected to be the same for both
cases, which is 0. Also, it was the production
code from the first test that made the second
test pass, so it is reasonable to say the first test
and second test are relatable and can be
combined.
TDD Walkthrough - Library Fine
Ok! First and second tests are out of the way, so
on to the third test. After making a major change
like that, run the tests to make sure everything is
passing.
Once that is green, move on to the third test!
For this test, 15 Hackos are due when the
returned book is 1 day late. So we expect 15
when we put in the dates Jan 08 2018 and Jan
07 2018.
TDD Walkthrough - Library Fine
Run the tests, and we have 1 passing and 1
failing test. This is shown in the upper left corner
as 1 green dot for the first/second test, and 1
red dot for the third test. Our new test is failing,
as expected.
Because the tests in the spec file don’t line up
with the test list, there may be some confusion
as to which test is which. Going forward, I only
refer to tests in the spec file unless otherwise
indicated. So our spec file has a first test, and
the new second test that we need to get
passing. Without failing the first one.
TDD Walkthrough - Library Fine
So how do we pass the second test, the fastest
way possible? The most straightforward way
would be, if the dates passed in are Jan 8 2018
and Jan 7 2018, then return 15.
Is this the implementation we want in the end?
Definitely no. But this implementation gets us
the passing test.
Now that our test is passing, we will fix this
implementation to work for all general cases.
TDD Walkthrough - Library Fine
The next step is to refactor. Specifically we want to generalize the implementation
for the second test, 15 Hackos per day the book is returned late.
What we have right now is called “fake it”. Our production code will pass the test
we wrote, but it doesn’t cover all the cases.
How do we change the code to cover all cases? There are two common
approaches: the Obvious Implementation, or Triangulation.
Triangulation is a method of taking small steps by writing additional tests. These
additional tests give clues to what the general implementation is. Use those clues
to make the appropriate changes. I will demonstrate this on the second test.
TDD Walkthrough - Library Fine
We should come up with another test case that
we know will fail, and is in the same category as
the second test. Let’s say a book is two days
late, and the fee due is 30 Hackos.
And we expect our new test to fail.
TDD Walkthrough - Library Fine
The fastest solution here will look like the last
one. If the dates look like this, then return 30.
Make sure the tests pass, then we can move on
to refactoring.
Now that we have two cases of the same rule,
we can look for a pattern and see if we can
refactor to better code.
For one thing, we know the fees due are
calculated as days overdue times 15. One step
at a time, we start by rewriting 30 as 2 * 15, and
15 as 1 * 15. Make sure you didn’t break
anything by rerunning the tests.
TDD Walkthrough - Library Fine
The 2 in 2 * 15 comes from the difference in
days between the return date and due date.
That is also true for the 1 in 1 * 15. The path to
better code in this case is to calculate the
difference in days between the two dates.
I start off by separating the return date and the
due date.
Then I assign each date to its own variable.
Then I fetch the day in each date.
The date starts as a string, so I need to convert
the days from strings to integers.
TDD Walkthrough - Library Fine
Now, I can calculate the fees due from the days
overdue. The return day minus the due day
gives the number of days overdue. Try that for
one case, make sure that passes.
Then do the same change for the other case,
and see that pass the tests too.
These two cases return the same thing now.
This means we can combine them. Do this by
putting the conditionals together. Remember,
when you make changes, run the tests!
TDD Walkthrough - Library Fine
We have this combined conditional, which is a
really long piece of code that is trying to say
something. What is it trying to say? If the day
returned is after the day due right? So then if the
day returned is greater than the day due, then
return number of days overdue times 15. That
sounds like our rule!
This may have seemed like a long winded
approach to this case. And it probably is,
considering how simple this rule is. When you
are confident in coding a simple piece of logic,
you can try to perform the Obvious
Implementation, which I will demonstrate.
TDD Walkthrough - Library Fine
A little cleaning up first, combining the test
cases of the second test.
Onto the next test case, which is overdue books
returned in the same year but different months.
From our test list, the test case we are using is a
book returned Feb 8 2018 and due on Jan 8
2018. 500 Hackos is due. Your tests should fail
at this time.
TDD Walkthrough - Library Fine
How to implement this? The third rule is very
similar to the second rule, except we calculate
the fee as the difference in months times 500
Hackos. We can borrow some of the code from
the second rule to implement the third rule. Get
the months from each date, and use their
difference to calculate the fee. The code for third
rule looks very much like the second rule, and
the tests pass!
While the obvious implementation worked out
this time, whenever you use this technique you
must be prepared to fix any special cases you
may have missed in your implementation.
TDD Walkthrough - Library Fine
Now for the last rule: a flat fee of 10000 Hackos
for overdue books returned in a later year. The
test case we chose for this rule is a book
returned Jan 1 2019 that was due on Jan 8
2018. 10000 Hackos are due.
TDD Walkthrough - Library Fine
The solution for this is fairly straightforward. As
long as the year returned is after the year due,
there is a flat fee of 10000 Hackos. We will need
to get the year numbers from the dates. It takes
a little string manipulation, but it will work. Once
you have the year numbers, the logic is about
the same as the other 2 rules we did earlier.
We have now passed tests for all 4 rules of the
Library Fine exercise! We have covered every
case on our test list.
TDD Walkthrough - Library Fine
You might notice that there are some cases that we do not pass. I left them out on
purpose so that you can go through the exercise yourself! The production code in
this walkthrough will not work when the days and months are double digits. I
suggest that you come up with your own, more comprehensive test list, and try to
use test driven development yourself to solve all cases of the Library Fine
problem. Good Luck!
TDD Walkthrough - Library Fine
For those who want to look at the source code, I have this walkthrough posted on
github here:
https://github.com/khapeterk/TDDWalkthroughLibraryFine

More Related Content

Similar to TDD Walkthrough - Library Fine

TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?
Dmitriy Nesteryuk
 
TDD & Refactoring
TDD & RefactoringTDD & Refactoring
TDD & Refactoring
Hernan Wilkinson
 
Kobi_H_2018_JustEnoughTesting_02_TestIL_handout
Kobi_H_2018_JustEnoughTesting_02_TestIL_handoutKobi_H_2018_JustEnoughTesting_02_TestIL_handout
Kobi_H_2018_JustEnoughTesting_02_TestIL_handout
Kobi Halperin
 
Intro to TDD
Intro to TDDIntro to TDD
Intro to TDD
Jason Nocks
 
Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...
Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...
Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...
Abdelkrim Boujraf
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
Ahmed Shreef
 
Pairing w developers_stpconpics
Pairing w developers_stpconpicsPairing w developers_stpconpics
Pairing w developers_stpconpics
Lanette Creamer
 
Blackboxtesting 02 An Example Test Series
Blackboxtesting 02 An Example Test SeriesBlackboxtesting 02 An Example Test Series
Blackboxtesting 02 An Example Test Series
nazeer pasha
 
Bigger Unit Test Are Better
Bigger Unit Test Are BetterBigger Unit Test Are Better
Bigger Unit Test Are Better
Peter Schuler
 
Hey You Got Your TDD in my SQL DB by Jeff McKenzie
Hey You Got Your TDD in my SQL DB by Jeff McKenzieHey You Got Your TDD in my SQL DB by Jeff McKenzie
Hey You Got Your TDD in my SQL DB by Jeff McKenzie
QA or the Highway
 
I'm a TDD cheat and I'm not afraid to admit it
I'm a TDD cheat and I'm not afraid to admit itI'm a TDD cheat and I'm not afraid to admit it
I'm a TDD cheat and I'm not afraid to admit it
Daniel Irvine
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
Igor Crvenov
 
Open source bridge testing antipatterns presentation
Open source bridge testing antipatterns presentationOpen source bridge testing antipatterns presentation
Open source bridge testing antipatterns presentation
mmrobins
 
Challenges-and-Consideration-in-Programming-Logic-and-Design...pptx
Challenges-and-Consideration-in-Programming-Logic-and-Design...pptxChallenges-and-Consideration-in-Programming-Logic-and-Design...pptx
Challenges-and-Consideration-in-Programming-Logic-and-Design...pptx
RusherGamer1
 
TDD, the way to better software | Dan Ursu | CodeWay 2015
TDD, the way to better software | Dan Ursu | CodeWay 2015TDD, the way to better software | Dan Ursu | CodeWay 2015
TDD, the way to better software | Dan Ursu | CodeWay 2015
YOPESO
 
Scrum and-xp-from-the-trenches 06 testing
Scrum and-xp-from-the-trenches 06 testingScrum and-xp-from-the-trenches 06 testing
Scrum and-xp-from-the-trenches 06 testing
Hossam Hassan
 
Upwork time log and difficulty 20160523
Upwork time log and difficulty 20160523Upwork time log and difficulty 20160523
Upwork time log and difficulty 20160523
Sharon Liu
 
Refactoring Legacy Code - true story
Refactoring Legacy Code - true storyRefactoring Legacy Code - true story
Refactoring Legacy Code - true story
Aki Salmi
 
A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...
A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...
A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...
Yuval Yeret
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Iranian Domain-Driven Design Community
 

Similar to TDD Walkthrough - Library Fine (20)

TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?
 
TDD & Refactoring
TDD & RefactoringTDD & Refactoring
TDD & Refactoring
 
Kobi_H_2018_JustEnoughTesting_02_TestIL_handout
Kobi_H_2018_JustEnoughTesting_02_TestIL_handoutKobi_H_2018_JustEnoughTesting_02_TestIL_handout
Kobi_H_2018_JustEnoughTesting_02_TestIL_handout
 
Intro to TDD
Intro to TDDIntro to TDD
Intro to TDD
 
Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...
Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...
Test-Driven Developments are Inefficient; Behavior-Driven Developments are a ...
 
Introduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed ShreefIntroduction to TDD (Test Driven development) - Ahmed Shreef
Introduction to TDD (Test Driven development) - Ahmed Shreef
 
Pairing w developers_stpconpics
Pairing w developers_stpconpicsPairing w developers_stpconpics
Pairing w developers_stpconpics
 
Blackboxtesting 02 An Example Test Series
Blackboxtesting 02 An Example Test SeriesBlackboxtesting 02 An Example Test Series
Blackboxtesting 02 An Example Test Series
 
Bigger Unit Test Are Better
Bigger Unit Test Are BetterBigger Unit Test Are Better
Bigger Unit Test Are Better
 
Hey You Got Your TDD in my SQL DB by Jeff McKenzie
Hey You Got Your TDD in my SQL DB by Jeff McKenzieHey You Got Your TDD in my SQL DB by Jeff McKenzie
Hey You Got Your TDD in my SQL DB by Jeff McKenzie
 
I'm a TDD cheat and I'm not afraid to admit it
I'm a TDD cheat and I'm not afraid to admit itI'm a TDD cheat and I'm not afraid to admit it
I'm a TDD cheat and I'm not afraid to admit it
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Open source bridge testing antipatterns presentation
Open source bridge testing antipatterns presentationOpen source bridge testing antipatterns presentation
Open source bridge testing antipatterns presentation
 
Challenges-and-Consideration-in-Programming-Logic-and-Design...pptx
Challenges-and-Consideration-in-Programming-Logic-and-Design...pptxChallenges-and-Consideration-in-Programming-Logic-and-Design...pptx
Challenges-and-Consideration-in-Programming-Logic-and-Design...pptx
 
TDD, the way to better software | Dan Ursu | CodeWay 2015
TDD, the way to better software | Dan Ursu | CodeWay 2015TDD, the way to better software | Dan Ursu | CodeWay 2015
TDD, the way to better software | Dan Ursu | CodeWay 2015
 
Scrum and-xp-from-the-trenches 06 testing
Scrum and-xp-from-the-trenches 06 testingScrum and-xp-from-the-trenches 06 testing
Scrum and-xp-from-the-trenches 06 testing
 
Upwork time log and difficulty 20160523
Upwork time log and difficulty 20160523Upwork time log and difficulty 20160523
Upwork time log and difficulty 20160523
 
Refactoring Legacy Code - true story
Refactoring Legacy Code - true storyRefactoring Legacy Code - true story
Refactoring Legacy Code - true story
 
A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...
A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...
A Software Tester's Travels from the Land of the Waterfall to the Land of Agi...
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
 

Recently uploaded

Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
Karya Keeper
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
NishanthaBulumulla1
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
dakas1
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 

Recently uploaded (20)

Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Project Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdfProject Management: The Role of Project Dashboards.pdf
Project Management: The Role of Project Dashboards.pdf
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
一比一原版(UMN毕业证)明尼苏达大学毕业证如何办理
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 

TDD Walkthrough - Library Fine

  • 1. TDD Walkthrough Library Fine Peter Kha: peter.kha@greatersum.com
  • 2. TDD Walkthrough - Library Fine Hello and welcome to my TDD Walkthrough! Today’s exercise is Library Fine, taken from HackerRank.com at the following URL: https://www.hackerrank.com/challenges/library-fi ne/problem
  • 3. TDD Walkthrough - Library Fine In these TDD Walkthroughs, I assume that my readers have basic knowledge of test driven development. I highly suggest having an understanding of TDD before going through this walkthrough. The following blog post explains the cycles of TDD. http://blog.cleancoder.com/uncle-bob/2014/12/1 7/TheCyclesOfTDD.html I also assume that my readers have knowledge of refactoring tools and terminology. If you need more information, this blog post on the six core refactorings will provide enough information. http://arlobelshee.com/the-core-6-refactorings/
  • 4. TDD Walkthrough - Library Fine For this exercise, I have the following already set up: Chrome browser Visual Studio Code or your personal IDE Jasmine testing framework (see my other blog on setting up: https://www.greatersum.com/tdd-setup-jasmine/) With the above already set up, let’s get started!
  • 5. TDD Walkthrough - Library Fine This walkthrough starts with an already set up Jasmine standalone project from my other blog post. From there, I will create the file that contains my tests.
  • 6. TDD Walkthrough - Library Fine There are various conventions for file names out there. I tend to use the affectionately dubbed kabob-case: library-fine.spec.js
  • 7. TDD Walkthrough - Library Fine This is a spec file. This file needs to be included in the Jasmine spec runner, so open up the SpecRunner.html file next. Look for the comment that says “include spec files here”, and include the spec file you just created.
  • 8. TDD Walkthrough - Library Fine We are now ready to write tests. Which tests do we write? Let’s start a test list. The first rule of Library Fine talks about books returned on or before the due date. What kinds of tests can come from this? I can think of 2. First, the book is returned today Jan 08, 2018 and it is due tomorrow Jan 09, 2018. It is returned before the due date, so no fee is due. Second, the book is returned today Jan 08, 2018 and it is due today Jan 08, 2018. It is returned on the due date, and no fee is due. Returned 01/08/2018 Due 01/09/2018 No Fee Due Returned 01/08/2018 Due 01/08/2018 No Fee Due
  • 9. TDD Walkthrough - Library Fine For the second rule, let’s say a book is returned Jan 08, 2018 and it was due Jan 07, 2018. It is one day late, which means 15 Hackos are due. For the third rule, let’s say a book is returned Feb 08, 2018 and it was due Jan 08, 2018. It was due the previous month, which means 500 Hackos are due. For the last rule, we’ll say a book was returned Jan 01, 2019 and it was due Jan 08, 2018. It was returned after the calendar year it was due and thus 10000 Hackos are due. Returned 01/08/2018 Due 01/07/2018 15 Hackos Due Returned 02/08/2018 Due 01/08/2018 500 Hackos Due Returned 01/01/2019 Due 01/08/2018 10000 Hackos Due
  • 10. TDD Walkthrough - Library Fine This test list looks like it covers all the rules for the Library Fine exercise. We have enough to get started. Returned 01/08/2018, Due 01/09/2018, No Fee Due Returned 01/08/2018, Due 01/08/2018, No Fee Due Returned 01/08/2018, Due 01/07/2018, 15 Hackos Due Returned 02/08/2018, Due 01/08/2018, 500 Hackos Due Returned 01/01/2019, Due 01/08/2018, 10000 Hackos Due
  • 11. TDD Walkthrough - Library Fine Let’s write our first test. First, we create the test suite: And then we write the test function: In our test function, we write what we are expecting:
  • 12. TDD Walkthrough - Library Fine At this point, you should be able to run your test runner HTML file by opening it in the browser, and see a failing test. Failing the test here is good! You haven’t written any production code yet, and that’s ok. What you did write is a test that will tell you when your code fulfilled a purpose, and that is to return a fee of 0 when the book returned before the due date. It’s not much, but we take one step at a time.
  • 13. TDD Walkthrough - Library Fine Ok, so what does the test runner say? libraryFine is not defined. That makes sense, we haven’t written anything called libraryFine yet. Let’s go make that function!
  • 14. TDD Walkthrough - Library Fine To keep the code organized well, the tests are contained in the spec file, in the spec folder. So then our source code should go in the source folder!
  • 15. TDD Walkthrough - Library Fine Our new source file will need to be included in the Spec Runner though, so let’s not forget to do that.
  • 16. TDD Walkthrough - Library Fine Now back to our source file. The first issue is that theTimeInWords is not defined, so let’s go define it.
  • 17. TDD Walkthrough - Library Fine You might be tempted to go implement all of the function right now. But bear with me and take one small step at a time. Let’s focus on the error at hand, and we’ll tackle each issue as they come up. That way we don’t write extra code for no reason. This is, after all, development that is driven by testing. So run the tests again. You can rerun the tests by refreshing the spec runner page.
  • 18. TDD Walkthrough - Library Fine Ok, different error message. Expected undefined to be 0. Well, the solution sounds simple. Make our function return 0!
  • 19. TDD Walkthrough - Library Fine This solution will make you cringe. It makes me cringe. But you never write more code than you need. That prevents you from wasting time on extra code, and it prevents you from writing code that can break other things in other ways. Focus on minimal design, and drive your code towards the functionality you want with tests.
  • 20. TDD Walkthrough - Library Fine Ok, that being said, our current test should pass. And it does! Good, we move on to the next test on our list.
  • 21. TDD Walkthrough - Library Fine With the first test case done, let’s do the second case: book returned and due on Jan 08, 2018. Run the tests, and it appears we’re already passing? Wait, that’s unexpected. If we were following the TDD cycle, our new test should be failing.
  • 22. TDD Walkthrough - Library Fine This second test was already passing because what we did for the first test fulfilled the second test. This means our second test doesn’t add anything new to production code. How useful is our second test then? It is normal during TDD to change your test list as you discover new things. Your test list is not perfect. It is a work in progress, and that is okay. So what do we do with this already passing test? People have different approaches. You can take it out. You can keep it there. If the situation fits, you can also put it together with another test.
  • 23. TDD Walkthrough - Library Fine I will combine the second test with the first test. The reasoning here is that the return from the function is expected to be the same for both cases, which is 0. Also, it was the production code from the first test that made the second test pass, so it is reasonable to say the first test and second test are relatable and can be combined.
  • 24. TDD Walkthrough - Library Fine Ok! First and second tests are out of the way, so on to the third test. After making a major change like that, run the tests to make sure everything is passing. Once that is green, move on to the third test! For this test, 15 Hackos are due when the returned book is 1 day late. So we expect 15 when we put in the dates Jan 08 2018 and Jan 07 2018.
  • 25. TDD Walkthrough - Library Fine Run the tests, and we have 1 passing and 1 failing test. This is shown in the upper left corner as 1 green dot for the first/second test, and 1 red dot for the third test. Our new test is failing, as expected. Because the tests in the spec file don’t line up with the test list, there may be some confusion as to which test is which. Going forward, I only refer to tests in the spec file unless otherwise indicated. So our spec file has a first test, and the new second test that we need to get passing. Without failing the first one.
  • 26. TDD Walkthrough - Library Fine So how do we pass the second test, the fastest way possible? The most straightforward way would be, if the dates passed in are Jan 8 2018 and Jan 7 2018, then return 15. Is this the implementation we want in the end? Definitely no. But this implementation gets us the passing test. Now that our test is passing, we will fix this implementation to work for all general cases.
  • 27. TDD Walkthrough - Library Fine The next step is to refactor. Specifically we want to generalize the implementation for the second test, 15 Hackos per day the book is returned late. What we have right now is called “fake it”. Our production code will pass the test we wrote, but it doesn’t cover all the cases. How do we change the code to cover all cases? There are two common approaches: the Obvious Implementation, or Triangulation. Triangulation is a method of taking small steps by writing additional tests. These additional tests give clues to what the general implementation is. Use those clues to make the appropriate changes. I will demonstrate this on the second test.
  • 28. TDD Walkthrough - Library Fine We should come up with another test case that we know will fail, and is in the same category as the second test. Let’s say a book is two days late, and the fee due is 30 Hackos. And we expect our new test to fail.
  • 29. TDD Walkthrough - Library Fine The fastest solution here will look like the last one. If the dates look like this, then return 30. Make sure the tests pass, then we can move on to refactoring. Now that we have two cases of the same rule, we can look for a pattern and see if we can refactor to better code. For one thing, we know the fees due are calculated as days overdue times 15. One step at a time, we start by rewriting 30 as 2 * 15, and 15 as 1 * 15. Make sure you didn’t break anything by rerunning the tests.
  • 30. TDD Walkthrough - Library Fine The 2 in 2 * 15 comes from the difference in days between the return date and due date. That is also true for the 1 in 1 * 15. The path to better code in this case is to calculate the difference in days between the two dates. I start off by separating the return date and the due date. Then I assign each date to its own variable. Then I fetch the day in each date. The date starts as a string, so I need to convert the days from strings to integers.
  • 31. TDD Walkthrough - Library Fine Now, I can calculate the fees due from the days overdue. The return day minus the due day gives the number of days overdue. Try that for one case, make sure that passes. Then do the same change for the other case, and see that pass the tests too. These two cases return the same thing now. This means we can combine them. Do this by putting the conditionals together. Remember, when you make changes, run the tests!
  • 32. TDD Walkthrough - Library Fine We have this combined conditional, which is a really long piece of code that is trying to say something. What is it trying to say? If the day returned is after the day due right? So then if the day returned is greater than the day due, then return number of days overdue times 15. That sounds like our rule! This may have seemed like a long winded approach to this case. And it probably is, considering how simple this rule is. When you are confident in coding a simple piece of logic, you can try to perform the Obvious Implementation, which I will demonstrate.
  • 33. TDD Walkthrough - Library Fine A little cleaning up first, combining the test cases of the second test. Onto the next test case, which is overdue books returned in the same year but different months. From our test list, the test case we are using is a book returned Feb 8 2018 and due on Jan 8 2018. 500 Hackos is due. Your tests should fail at this time.
  • 34. TDD Walkthrough - Library Fine How to implement this? The third rule is very similar to the second rule, except we calculate the fee as the difference in months times 500 Hackos. We can borrow some of the code from the second rule to implement the third rule. Get the months from each date, and use their difference to calculate the fee. The code for third rule looks very much like the second rule, and the tests pass! While the obvious implementation worked out this time, whenever you use this technique you must be prepared to fix any special cases you may have missed in your implementation.
  • 35. TDD Walkthrough - Library Fine Now for the last rule: a flat fee of 10000 Hackos for overdue books returned in a later year. The test case we chose for this rule is a book returned Jan 1 2019 that was due on Jan 8 2018. 10000 Hackos are due.
  • 36. TDD Walkthrough - Library Fine The solution for this is fairly straightforward. As long as the year returned is after the year due, there is a flat fee of 10000 Hackos. We will need to get the year numbers from the dates. It takes a little string manipulation, but it will work. Once you have the year numbers, the logic is about the same as the other 2 rules we did earlier. We have now passed tests for all 4 rules of the Library Fine exercise! We have covered every case on our test list.
  • 37. TDD Walkthrough - Library Fine You might notice that there are some cases that we do not pass. I left them out on purpose so that you can go through the exercise yourself! The production code in this walkthrough will not work when the days and months are double digits. I suggest that you come up with your own, more comprehensive test list, and try to use test driven development yourself to solve all cases of the Library Fine problem. Good Luck!
  • 38. TDD Walkthrough - Library Fine For those who want to look at the source code, I have this walkthrough posted on github here: https://github.com/khapeterk/TDDWalkthroughLibraryFine