SlideShare ist ein Scribd-Unternehmen logo
1 von 37
Downloaden Sie, um offline zu lesen
TDD Walkthrough
Encryption
Peter Kha: peter.kha@greatersum.com
TDD Walkthrough - Encryption
Hello and welcome to my TDD Walkthrough!
Today’s exercise is Encryption, taken from
hackerrank.com at the following URL:
https://www.hackerrank.com/challenges/encrypti
on/problem
TDD Walkthrough - Encryption
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 - Encryption
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 - Encryption
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 - Encryption
There are various conventions for file names out
there. I learned to name all my test files Spec
files. I will name my spec file encryption.spec.js.
TDD Walkthrough - Encryption
The spec 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 - Encryption
We are now ready to write tests. Which tests do
we write? Let’s start a test list.
The problem description on hackerrank.com
includes 3 good examples for our test list.
In situations where you’re not familiar with the
problem, you might be afraid to think of up a
comprehensive list of tests that cover all
situations. It’s ok to make an imperfect test list.
Just have a few tests, enough to get started.
haveaniceday => hae and via ecy
feedthedog => fto ehg ee dd
chillout => clu hlt io
TDD Walkthrough - Encryption
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 - Encryption
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. It’s not much, but we take one step at a time.
TDD Walkthrough - Encryption
Ok, so what does the test runner say?
encrypt is not defined. That makes sense, we
haven’t written anything called encrypt yet.
Let’s go make that function!
TDD Walkthrough - Encryption
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 - Encryption
Our new source file will need to be included in
the Spec Runner though, so let’s not forget to do
that.
TDD Walkthrough - Encryption
Now back to our source file. The first issue is
that encrypt is not defined, so let’s go define it.
TDD Walkthrough - Encryption
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 - Encryption
Ok, different error message. Expected
undefined to be ‘hae and via ecy’.
Well, the solution sounds simple. Make our
function return exactly that string!
TDD Walkthrough - Encryption
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 - Encryption
Ok, that being said, our current test should pass.
And it does!
Although unnecessary, I take a quick look at our
function to see if there is any refactoring to be
done. Our function is very simple, so no.
We move on to the next test on our list.
TDD Walkthrough - Encryption
With the first test case done, let’s do the second
case: “feedthedog” returns “fto ehg ee dd”
Run the tests, and we fail as expected.
TDD Walkthrough - Encryption
What’s the fastest way to make that test pass?
Check the input string, and if it is “feedthedog”,
return the encrypted string. This is not the
implementation we want to end up with, but it is
good enough for now.
Do our tests pass? Yes. Now for the fun part:
Refactoring.
TDD Walkthrough - Encryption
In the refactoring step, you look for opportunities to improve the code while
passing your current tests, to make sure you didn’t break anything with your
changes.
We can see that we hardcoded our returns and the checking of the input string.
We only handle specific inputs. We need to generalize our implementation. This
will be the start of a large refactoring phase. Many arbitrary design decisions will
be made in the following steps.
TDD Walkthrough - Encryption
I usually use one of two approaches to discovering the implementation of a
solution. I might draw out the logic on a whiteboard, or I make small changes in
the code to eventually approach the implementation solution. Drawing out the
solution on a whiteboard makes it easier to visualize the solution. But you still
have to translate that visualization into code, which is not always simple.
I will demonstrate how to make small changes to the code safely and progress
towards the generalized implementation we want. There will be many small steps,
and the slow pace may frustrate you. But going at this slow pace with small steps
will give you confidence that your implementation will work, and you will spend
less time fixing mistakes.
TDD Walkthrough - Encryption
The first thing we can do is eliminate the
hardcoded return. I will introduce a variable to
replace it. And as always, rerun tests to make
sure they all pass.
What else do we see here? The result is a
series of strings. I will break up the result into a
bunch of blocks, separated by a space. We are
starting to see a pattern here, but the next step
will make it very obvious.
TDD Walkthrough - Encryption
The letters of each block come from the input
string. At very specific indexes too. I can replace
the hardcoded first block with references to
certain characters in the input string. I
experiment by making this change only on the
first block. Did it work? Yes, the tests still pass!
Implement this indexing pattern for the rest of
the blocks, and make sure the tests pass. Now
we feel more comfortable that this function can
handle different strings. But we’re not done yet!
There are many more patterns to implement.
TDD Walkthrough - Encryption
There’s a pattern among the indexes too. The
differences in the indexes are 4 and 8. Let’s
make the code express that increment.
So what does this mean? If you look at the
problem description, they tell you that the rows
and columns of the grid they use for the
encryption are based on the length of the string.
There are 3 rows and 4 columns in the grid for
this case. 4 columns seems to match 4 blocks,
and also matches the difference of 4 between
the indexes. The number of columns seems to
be what defines the indexes and the number of
blocks.
TDD Walkthrough - Encryption
I want to express the increments as multiples of
the number of columns. So I express the
indexes as multiples of 4.
I am starting to see a consistency among these
blocks. I separate them into their own lines. This
makes it very easy to compare them and
recognize the pattern.
TDD Walkthrough - Encryption
I add one little change to the first character of
each block, and now the pattern is very clear.
The index consists of 3 numbers. The first is the
column index, 0 thru 3. The second is the row
index, 0 thru 2. The third is the number of
columns, 4.
All of these numbers are calculated from the
length of the input string, so we will need to
calculate those first before proceeding.
TDD Walkthrough - Encryption
According to the problem description, the rows
is the floor function of the square root of the
length. The columns is the ceiling of the square
root of the length.
Now that we have our numbers, we can
implement a for loop for the row index. I make
the change only to the first block as a test, to
make sure it works. As always, whenever we
make changes, run the tests!
TDD Walkthrough - Encryption
Two things left to generalize.
Next, I change the 4 into the number of
columns. Tests should still pass. This pattern
should work for all the blocks now, keeping in
mind that the first number, the column index, is
different for each block.
The last thing to generalize here is the column
index. I do make some design decisions here
arbitrarily. Because these blocks are separated
by spaces, my plan is to put these blocks into an
array, and join them together with a space
separator. I will begin to change my code in that
direction.
TDD Walkthrough - Encryption
So, my result is an array now instead of a string.
I want to push the blocks of strings into the
array. So I update each block to create a
temporary string (I called it block. Seems
appropriate). This block is pushed onto the
result array. Do this for each block. Then return
the array joined together with a single space.
Make sure the tests still pass.
How did I decide to make a big leap like that?
Just a hunch. There are many ways to do
things, especially in software development.
Experience will teach you when and why to use
some of instead of others. You are welcome to
implement this any other way.
TDD Walkthrough - Encryption
Finally, we can generalize the implementation of
the column index, which consolidates most of
this code and removes the duplication.
Implement a for loop for the column index. Put
the code for a block inside the for loop and
change the number that increments to
columnIndex. And now this double for loop
should build the encrypted string for many
scenarios. My idea of testing that would be to
remove the if statement for the case of
“feedthedog”.
TDD Walkthrough - Encryption
I remove the if statement, but our test fails!
That’s not good. What happened?
Some investigation will reveal that we tried to
access indexes of the input string that didn’t
exist. Looks like I’ll have to include an if
statement to check if the index is bigger than the
length of the string. Good TDD practice would
be to go back to passing state (this means
putting the if statement back), and then make
the change and run the tests again.
TDD Walkthrough - Encryption
I remove the if statement again. This time we
pass the tests.
And that was all one refactoring step! It was a lot
of work. Yes, we could have gone faster. But as
mentioned before, going this slow and taking
steps this small reduces wasted time in fixing
mistakes.I would like to do one more refactoring,
which is to introduce a variable for the string
index, to make it easier to read. As always, run
the tests to make sure they pass.
TDD Walkthrough - Encryption
We are nearing the end! We have one last test
to add, which is “chillout => clu hlt io”.
You might think that this test will pass, since our
implementation looks good as is. But it doesn’t!
Why is that?
Turns out, there is a little rule in the encryption
problem description that goes “rows * columns >
L”, where L is the length of the string.
In the “chillout” case, rows is 2, columns is 3, the
grid has an area of 6 characters, and the string
is 8 characters long. That doesn’t work!
c h i
l l o
Where does the u
and the t go?
TDD Walkthrough - Encryption
The fastest solution I came up with was to add 1
to the number of rows if the area of the grid was
smaller than the length of the input string. That
satisfies the condition that rows * columns is
always greater than the length of the input
string. That makes the test pass.
And that’s it! This is the completed Encryption
solution. There is room for improvement in this
code in terms of refactoring and structure. I will
let you guys figure out what those improvements
might be.
TDD Walkthrough - Encryption
Some final thoughts about this problem.
I did mention before that I made some arbitrary design decisions. The double for
loop was one of them. There are other ways to implement the solution. I
considered trying a for each type of loop, but I wasn’t sure how much effort it
would be to implement. Be sure to use source control on your code, and commit
often. That way, if you make a mistake, you can roll back to an earlier commit and
take a different path without too much hassle.
I hope that this walkthrough helps you understand how to implement test driven
development for your assignments. Good luck!
TDD Walkthrough - Encryption
For those who want to look at the source code, I have this walkthrough posted on
github here:
https://github.com/khapeterk/Encryption

Weitere ähnliche Inhalte

Was ist angesagt?

TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven DevelopmentTung Nguyen Thanh
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy CodeAdam Culp
 
【Edd workshop@140725】TDD introduction_Andy Huang
【Edd workshop@140725】TDD introduction_Andy Huang 【Edd workshop@140725】TDD introduction_Andy Huang
【Edd workshop@140725】TDD introduction_Andy Huang EZTABLE
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeAmar Shah
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And RefactoringNaresh Jain
 
How to complement TDD with static analysis
How to complement TDD with static analysisHow to complement TDD with static analysis
How to complement TDD with static analysisPVS-Studio
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief exampleJeremy Kendall
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your codePascal Larocque
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An IntroductionGiorgio Vespucci
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionDionatan default
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentConsulthinkspa
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelinesAnkur Goyal
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
TDD Walkthrough - Library Fine
TDD Walkthrough - Library FineTDD Walkthrough - Library Fine
TDD Walkthrough - Library FinePeterKha2
 

Was ist angesagt? (20)

TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 
Tdd
TddTdd
Tdd
 
Refactoring Legacy Code
Refactoring Legacy CodeRefactoring Legacy Code
Refactoring Legacy Code
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
【Edd workshop@140725】TDD introduction_Andy Huang
【Edd workshop@140725】TDD introduction_Andy Huang 【Edd workshop@140725】TDD introduction_Andy Huang
【Edd workshop@140725】TDD introduction_Andy Huang
 
Working Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in PracticeWorking Effectively with Legacy Code: Lessons in Practice
Working Effectively with Legacy Code: Lessons in Practice
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
How to complement TDD with static analysis
How to complement TDD with static analysisHow to complement TDD with static analysis
How to complement TDD with static analysis
 
Tdd in php a brief example
Tdd in php   a brief exampleTdd in php   a brief example
Tdd in php a brief example
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
Refactoring - An Introduction
Refactoring - An IntroductionRefactoring - An Introduction
Refactoring - An Introduction
 
TDD Flow: The Mantra in Action
TDD Flow: The Mantra in ActionTDD Flow: The Mantra in Action
TDD Flow: The Mantra in Action
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
PHPUnit - Unit testing
PHPUnit - Unit testingPHPUnit - Unit testing
PHPUnit - Unit testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
TDD Walkthrough - Library Fine
TDD Walkthrough - Library FineTDD Walkthrough - Library Fine
TDD Walkthrough - Library Fine
 

Ähnlich wie TDD Walkthrough - Encryption

TDD Walkthrough - The Time in Words
TDD Walkthrough -  The Time in WordsTDD Walkthrough -  The Time in Words
TDD Walkthrough - The Time in WordsPeterKha2
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonCefalo
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven DevelopmentFerdous Mahmud Shaon
 
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
 
Beyond Testing: Specs and Behavior Driven Development
Beyond Testing: Specs and Behavior  Driven DevelopmentBeyond Testing: Specs and Behavior  Driven Development
Beyond Testing: Specs and Behavior Driven DevelopmentRabble .
 
Unit testing
Unit testingUnit testing
Unit testingPiXeL16
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentbhochhi
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Developmentjakubkoci
 
Understanding Why Testing is Importaint
Understanding Why Testing is ImportaintUnderstanding Why Testing is Importaint
Understanding Why Testing is ImportaintSana Nasar
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit TestingWen-Tien Chang
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Gianluca Padovani
 
Adopting tdd in the workplace
Adopting tdd in the workplaceAdopting tdd in the workplace
Adopting tdd in the workplaceDonny Wals
 
Adopting tdd in the workplace
Adopting tdd in the workplaceAdopting tdd in the workplace
Adopting tdd in the workplaceDonny Wals
 
Lập trình hướng kiểm thử - Test Driven development
Lập trình hướng kiểm thử - Test Driven developmentLập trình hướng kiểm thử - Test Driven development
Lập trình hướng kiểm thử - Test Driven developmentAnh Lê
 

Ähnlich wie TDD Walkthrough - Encryption (20)

TDD Walkthrough - The Time in Words
TDD Walkthrough -  The Time in WordsTDD Walkthrough -  The Time in Words
TDD Walkthrough - The Time in Words
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Tdd is not about testing
Tdd is not about testingTdd is not about testing
Tdd is not about testing
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud Shaon
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven Development
 
TDD a piccoli passi
TDD a piccoli passiTDD a piccoli passi
TDD a piccoli passi
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
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
 
Beyond Testing: Specs and Behavior Driven Development
Beyond Testing: Specs and Behavior  Driven DevelopmentBeyond Testing: Specs and Behavior  Driven Development
Beyond Testing: Specs and Behavior Driven Development
 
Unit testing
Unit testingUnit testing
Unit testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Understanding Why Testing is Importaint
Understanding Why Testing is ImportaintUnderstanding Why Testing is Importaint
Understanding Why Testing is Importaint
 
Testacular
TestacularTestacular
Testacular
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 
Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)Tdd is not about testing (C++ version)
Tdd is not about testing (C++ version)
 
Adopting tdd in the workplace
Adopting tdd in the workplaceAdopting tdd in the workplace
Adopting tdd in the workplace
 
Adopting tdd in the workplace
Adopting tdd in the workplaceAdopting tdd in the workplace
Adopting tdd in the workplace
 
Lập trình hướng kiểm thử - Test Driven development
Lập trình hướng kiểm thử - Test Driven developmentLập trình hướng kiểm thử - Test Driven development
Lập trình hướng kiểm thử - Test Driven development
 

Kürzlich hochgeladen

%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburgmasabamasaba
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsBert Jan Schrijver
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Kürzlich hochgeladen (20)

%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
%in Lydenburg+277-882-255-28 abortion pills for sale in Lydenburg
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Generic or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

TDD Walkthrough - Encryption

  • 1. TDD Walkthrough Encryption Peter Kha: peter.kha@greatersum.com
  • 2. TDD Walkthrough - Encryption Hello and welcome to my TDD Walkthrough! Today’s exercise is Encryption, taken from hackerrank.com at the following URL: https://www.hackerrank.com/challenges/encrypti on/problem
  • 3. TDD Walkthrough - Encryption 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 - Encryption 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 - Encryption 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 - Encryption There are various conventions for file names out there. I learned to name all my test files Spec files. I will name my spec file encryption.spec.js.
  • 7. TDD Walkthrough - Encryption The spec 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 - Encryption We are now ready to write tests. Which tests do we write? Let’s start a test list. The problem description on hackerrank.com includes 3 good examples for our test list. In situations where you’re not familiar with the problem, you might be afraid to think of up a comprehensive list of tests that cover all situations. It’s ok to make an imperfect test list. Just have a few tests, enough to get started. haveaniceday => hae and via ecy feedthedog => fto ehg ee dd chillout => clu hlt io
  • 9. TDD Walkthrough - Encryption 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:
  • 10. TDD Walkthrough - Encryption 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. It’s not much, but we take one step at a time.
  • 11. TDD Walkthrough - Encryption Ok, so what does the test runner say? encrypt is not defined. That makes sense, we haven’t written anything called encrypt yet. Let’s go make that function!
  • 12. TDD Walkthrough - Encryption 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!
  • 13. TDD Walkthrough - Encryption Our new source file will need to be included in the Spec Runner though, so let’s not forget to do that.
  • 14. TDD Walkthrough - Encryption Now back to our source file. The first issue is that encrypt is not defined, so let’s go define it.
  • 15. TDD Walkthrough - Encryption 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.
  • 16. TDD Walkthrough - Encryption Ok, different error message. Expected undefined to be ‘hae and via ecy’. Well, the solution sounds simple. Make our function return exactly that string!
  • 17. TDD Walkthrough - Encryption 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.
  • 18. TDD Walkthrough - Encryption Ok, that being said, our current test should pass. And it does! Although unnecessary, I take a quick look at our function to see if there is any refactoring to be done. Our function is very simple, so no. We move on to the next test on our list.
  • 19. TDD Walkthrough - Encryption With the first test case done, let’s do the second case: “feedthedog” returns “fto ehg ee dd” Run the tests, and we fail as expected.
  • 20. TDD Walkthrough - Encryption What’s the fastest way to make that test pass? Check the input string, and if it is “feedthedog”, return the encrypted string. This is not the implementation we want to end up with, but it is good enough for now. Do our tests pass? Yes. Now for the fun part: Refactoring.
  • 21. TDD Walkthrough - Encryption In the refactoring step, you look for opportunities to improve the code while passing your current tests, to make sure you didn’t break anything with your changes. We can see that we hardcoded our returns and the checking of the input string. We only handle specific inputs. We need to generalize our implementation. This will be the start of a large refactoring phase. Many arbitrary design decisions will be made in the following steps.
  • 22. TDD Walkthrough - Encryption I usually use one of two approaches to discovering the implementation of a solution. I might draw out the logic on a whiteboard, or I make small changes in the code to eventually approach the implementation solution. Drawing out the solution on a whiteboard makes it easier to visualize the solution. But you still have to translate that visualization into code, which is not always simple. I will demonstrate how to make small changes to the code safely and progress towards the generalized implementation we want. There will be many small steps, and the slow pace may frustrate you. But going at this slow pace with small steps will give you confidence that your implementation will work, and you will spend less time fixing mistakes.
  • 23. TDD Walkthrough - Encryption The first thing we can do is eliminate the hardcoded return. I will introduce a variable to replace it. And as always, rerun tests to make sure they all pass. What else do we see here? The result is a series of strings. I will break up the result into a bunch of blocks, separated by a space. We are starting to see a pattern here, but the next step will make it very obvious.
  • 24. TDD Walkthrough - Encryption The letters of each block come from the input string. At very specific indexes too. I can replace the hardcoded first block with references to certain characters in the input string. I experiment by making this change only on the first block. Did it work? Yes, the tests still pass! Implement this indexing pattern for the rest of the blocks, and make sure the tests pass. Now we feel more comfortable that this function can handle different strings. But we’re not done yet! There are many more patterns to implement.
  • 25. TDD Walkthrough - Encryption There’s a pattern among the indexes too. The differences in the indexes are 4 and 8. Let’s make the code express that increment. So what does this mean? If you look at the problem description, they tell you that the rows and columns of the grid they use for the encryption are based on the length of the string. There are 3 rows and 4 columns in the grid for this case. 4 columns seems to match 4 blocks, and also matches the difference of 4 between the indexes. The number of columns seems to be what defines the indexes and the number of blocks.
  • 26. TDD Walkthrough - Encryption I want to express the increments as multiples of the number of columns. So I express the indexes as multiples of 4. I am starting to see a consistency among these blocks. I separate them into their own lines. This makes it very easy to compare them and recognize the pattern.
  • 27. TDD Walkthrough - Encryption I add one little change to the first character of each block, and now the pattern is very clear. The index consists of 3 numbers. The first is the column index, 0 thru 3. The second is the row index, 0 thru 2. The third is the number of columns, 4. All of these numbers are calculated from the length of the input string, so we will need to calculate those first before proceeding.
  • 28. TDD Walkthrough - Encryption According to the problem description, the rows is the floor function of the square root of the length. The columns is the ceiling of the square root of the length. Now that we have our numbers, we can implement a for loop for the row index. I make the change only to the first block as a test, to make sure it works. As always, whenever we make changes, run the tests!
  • 29. TDD Walkthrough - Encryption Two things left to generalize. Next, I change the 4 into the number of columns. Tests should still pass. This pattern should work for all the blocks now, keeping in mind that the first number, the column index, is different for each block. The last thing to generalize here is the column index. I do make some design decisions here arbitrarily. Because these blocks are separated by spaces, my plan is to put these blocks into an array, and join them together with a space separator. I will begin to change my code in that direction.
  • 30. TDD Walkthrough - Encryption So, my result is an array now instead of a string. I want to push the blocks of strings into the array. So I update each block to create a temporary string (I called it block. Seems appropriate). This block is pushed onto the result array. Do this for each block. Then return the array joined together with a single space. Make sure the tests still pass. How did I decide to make a big leap like that? Just a hunch. There are many ways to do things, especially in software development. Experience will teach you when and why to use some of instead of others. You are welcome to implement this any other way.
  • 31. TDD Walkthrough - Encryption Finally, we can generalize the implementation of the column index, which consolidates most of this code and removes the duplication. Implement a for loop for the column index. Put the code for a block inside the for loop and change the number that increments to columnIndex. And now this double for loop should build the encrypted string for many scenarios. My idea of testing that would be to remove the if statement for the case of “feedthedog”.
  • 32. TDD Walkthrough - Encryption I remove the if statement, but our test fails! That’s not good. What happened? Some investigation will reveal that we tried to access indexes of the input string that didn’t exist. Looks like I’ll have to include an if statement to check if the index is bigger than the length of the string. Good TDD practice would be to go back to passing state (this means putting the if statement back), and then make the change and run the tests again.
  • 33. TDD Walkthrough - Encryption I remove the if statement again. This time we pass the tests. And that was all one refactoring step! It was a lot of work. Yes, we could have gone faster. But as mentioned before, going this slow and taking steps this small reduces wasted time in fixing mistakes.I would like to do one more refactoring, which is to introduce a variable for the string index, to make it easier to read. As always, run the tests to make sure they pass.
  • 34. TDD Walkthrough - Encryption We are nearing the end! We have one last test to add, which is “chillout => clu hlt io”. You might think that this test will pass, since our implementation looks good as is. But it doesn’t! Why is that? Turns out, there is a little rule in the encryption problem description that goes “rows * columns > L”, where L is the length of the string. In the “chillout” case, rows is 2, columns is 3, the grid has an area of 6 characters, and the string is 8 characters long. That doesn’t work! c h i l l o Where does the u and the t go?
  • 35. TDD Walkthrough - Encryption The fastest solution I came up with was to add 1 to the number of rows if the area of the grid was smaller than the length of the input string. That satisfies the condition that rows * columns is always greater than the length of the input string. That makes the test pass. And that’s it! This is the completed Encryption solution. There is room for improvement in this code in terms of refactoring and structure. I will let you guys figure out what those improvements might be.
  • 36. TDD Walkthrough - Encryption Some final thoughts about this problem. I did mention before that I made some arbitrary design decisions. The double for loop was one of them. There are other ways to implement the solution. I considered trying a for each type of loop, but I wasn’t sure how much effort it would be to implement. Be sure to use source control on your code, and commit often. That way, if you make a mistake, you can roll back to an earlier commit and take a different path without too much hassle. I hope that this walkthrough helps you understand how to implement test driven development for your assignments. Good luck!
  • 37. TDD Walkthrough - Encryption For those who want to look at the source code, I have this walkthrough posted on github here: https://github.com/khapeterk/Encryption