25

Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think
Page 2: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Informed Test-DrivenDevelopment

Ralf Westphal

This book is for sale at http://leanpub.com/informedTDD

This version was published on 2014-06-18

This is a Leanpub book. Leanpub empowers authors andpublishers with the Lean Publishing process. Lean Publishing isthe act of publishing an in-progress ebook using lightweight toolsand many iterations to get reader feedback, pivot until you havethe right book and build traction once you do.

©2014 Ralf Westphal

Page 3: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Contents

The Self-Similar Software Development Process . . . . . . 1It´s the requirements, stupid! . . . . . . . . . . . . . . . . 1Architecture for qualities . . . . . . . . . . . . . . . . . . 2Functionality for the problem domain . . . . . . . . . . . 4Continuity in designing software on all levels . . . . . . 5

Recursively Descending Test-Driven Development Aidedby Thinking . . . . . . . . . . . . . . . . . . . . . . . . 7

Using Mocks to Allow for True Stepwise Refinement . . . 15“Traditional” TDD . . . . . . . . . . . . . . . . . . . . . 15Informed TDD (ITDD) . . . . . . . . . . . . . . . . . . . 19

Release Notes . . . . . . . . . . . . . . . . . . . . . . . . . 21

About the Author . . . . . . . . . . . . . . . . . . . . . . . 22

Page 4: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

The Self-Similar SoftwareDevelopment ProcessI read, with interest, Robert C. Martin´s comment¹ on Justin Searl´scritique² of a common TDD teaching approach. Strange it was tosee “the good uncle” to be so upset about Justin´s article. Why doeshe take it so personally, it seems, that someone is not content withthe state of TDD-affairs? Why salting Justin´s earth?

Anyway… what I wanted to express is my disagreement withRobert C. Martin´s idea of a “Domain Discontinuity”. He proposesthere to be two levels in software system design: one, wherethinking before implementing is good, and another one where it´sbad. The first being architecture, the second being “the problemdomain”.

Unfortunately, he does not define what he means by “architecture”.And his definition of “problem domain” is shallow at best: businessrules.

But why this dichotomy?

It´s the requirements, stupid!

Strangely the term “requirements” occures only once in Robert C.Martin´s article. He associates it with tests. I completely agree withthat. But why stop there?

Each and every trait of a software system – the look of theUI, the performance of some calculation, the distribution of code

¹http://ht.ly/t2UdI²http://blog.testdouble.com/posts/2014-01-25-the-failures-of-intro-to-tdd.html

Page 5: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

The Self-Similar Software Development Process 2

across clients and servers, the choice of persistence technology, thenumber of classes, the interfaces of those classes etc. – must betraceable to some requirement. This is true for coarse grained traitsas well as fine grained traits.

The basic categories of requirements to me seem to be:

• functional requirements or functionality for short• non-functional requirements or (primary) qualities for short,e.g. performance, scalability, security, usability etc.

• evolvability, i.e. a special quality regarding the flexibility toadapt the software system to new requirements

• production efficiency, i.e. a special quality regarding the easeand speed to implement requirements; it´s a quality of thedevelopment process

Software development thus is the art (or craft or disciplin) ofmakingthe right choices from a set of options to best fulfill the concreterequirements falling into those categories.

Architecture for qualities

With requirements put first the question again is: What´s softwarearchitecture in particular about?

My simple answer to this perennial question is: Software architec-ture is about designing structures to fulfill non-functional require-ments aka qualities.

I don´t care much about whether architects need to be top commu-nicators in order to do this job. I don´t care much about whetherthey need to be top notch coders to do this job. I don´t care abouttheir tools or the level of their architecture documentation. Just dowhatever is necessary to transform requirements into “ideas” ofstructures for code (and other artifacts).

Page 6: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

The Self-Similar Software Development Process 3

Architects don´t build, they design. That means they think –before someone else implements. (Please get me right, when I say“architect” I don´t mean a person but a role. The same person canbe an architect at one moment and something else in the nextmoment. I do not advocate special architect job positions. Rightto the contrary: I think each and every developer should hone hisarchitecture skills.)

Sure, architecting software is not easy. Not because so manyparadigms and technologies need to be taken into consideration,but because of the need to balance. Qualities are contradictory attimes. They can pull software structures into opposite directions.Designing for performance might impede evolvability. Designingfor security might impede performance.

Architects thus need to deliberate much. They need to think.

Yes, not too much. I know. BDUF´s still bad. But some thinking isin order. All else would negate thousands of years of engineeringsuccess. Where the requirements are clear, up-front thinking leadsto a solution – however tentative that might be.

So when does thinking about qualities end? Does it end afterchoosing MVVM over MVC and encapsulating MongoDB accesswith some kind of adapter or moving business logic into storedprocedures?

I won´t say so. Because architecture is whereever anybody decidesanything with regard to qualities, especially when it´s pertaining tothe software´s structure. That means, architecture is at work while(!) doing TDD. Because what drives the refactoring of a solution?It´s some quality, not functionality. Why extract a method, a class?Why segregate interfaces? Why follow IoC and do DI? That´s allarchitectural questions.

There´s nothing sacred or lofty about architecture. It´s simply abouta couple of issues that need to be resolved, quality issues. Anybodywith the right knowledge and capabilities can be an architect. In

Page 7: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

The Self-Similar Software Development Process 4

fact every developer is every day.

Functionality for the problem domain

The second term Robert C. Martin uses is “problem domain”. Withthe above categories of requirements I guess I know what he meansby that: functionality. Not quality, but functionality. That´s fairenough.

And he says, tests should be used to formalize functional require-ments (i.e. desired behavior) before the implementation. I agreewith that, too.

What I don´t get, though, is: Why not continue to apply the humanbrain afterwards? Or even before? Why devalue thinking in theform of “thinking up a design”?

If (functional) requirements are clear enough to hard code tests,why aren´t they clear enough to at least come up with a solutionsketch for the part of the problem domain in focus?

Again and again I have seen experienced developers fail at simpleproblem domains like “kata roman numerals”. They don´t failbecause they lack extraordinary TDD skills. No, they fail becausethey have little practice in actually “thinking about solutions beforecoding”. Theír tool chest contains only a single tool: code.

So what to do about refactoring? Well, where should an idea of abetter structure come fromwhen you´re not used to thinking beforecoding? Refactoring as the third TDD step just defers thinking tothe last possible moment – and beyond, as the many TDD examplesshowwhere notmuch refactoringwas done. Refactoring is optional.Nothing forces refactoring in TDD. That´s why Keith Braithwaitecame up with “TDD as if you meant it”³.

But why then say, “They just haven´t gotten it! They need to learn todo better TDD!”? Why not question for a moment the “traditional”

³http://www.infoq.com/presentations/TDD-as-if-You-Meant-It

Page 8: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

The Self-Similar Software Development Process 5

TDD approach? Why not – as Justin does – introduce at least somethinking before coding?

The cleanliness of code which TDD might aim at also is just oneof many qualities – which needs to be balanced against others, likeproduction efficiency.

At least I´m happy to sacrifice some elegance and cleanliness forefficiency and readability. That´s why I think before I write the firsttest, no, even before I prioritize test cases. And I think about thedesign of the code. What functional (!) structure should it have tomake it easy to understand? How does that collide or play togetherwith testability?

So I´m an architect while doing TDD. I´m a problem solver. Andmore often than not I´m not surprised by the coded solutions,but see them to comply with my ideas of how a solution shouldlook like. I know the steps of converting arabic numbers to romannumbers before (!) I start coding. In fact I´m writing code to matchmy conceptual (algorithmic) approach.

Continuity in designing software on alllevels

Architecture is thinking about structures, that is structures todeliver qualities. Solving the challenges of the problem domainist about structures, that is structures to deliver functionality (inaccordance with qualities).

Software is a self-similar system with many levels. It consists ofwholes containing parts being wholes again for even smaller partsetc. “It´s holons⁴ all the way down” to use a term Arthur Koestlerhas coined. And because of that the same principles apply on alllevels, not just DRY, SRP etc., but also “thinking helps”.

⁴http://en.wikipedia.org/wiki/Holon_(philosophy)

Page 9: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

The Self-Similar Software Development Process 6

There is no discontinuity as Robert C. Martin suggest. Right to thecontrary! Like there is strategic design, there is tactic design andsituational design. And that means, there is thinking before doing.There is engineering before hammering and welding.

My interpretation of what Justin has written is: Use your headbefore you sling the code to make a test green. With that I agreewholeheartedly, even though I might disagree with some details ofhis approach.

The dichotomy Robert C. Martin suggests between architectureand problem domain does not warrant a fundamentally differentapproach to design on those different levels. Because design is aboutstructure (and thus about options and decisions). And structureshould not be an afterthought or be stumbled upon.

But before someone accuses me of advocating waterfall develop-ment: Yes, I do! :-) Because that´s how the world works. Before thereis a man made structure, man better has thought about it. Designup-front is inevitable. Even if you want to you cannot avoid it. Youjust can hide it or deny it. But it´s there.

The question thus is not whether to design before coding or not.It´s not about waterfall or not. It´s just about the scope. If the scopeencompasses so many requirements it would take you 3 months todesign and 8 to implement, then that´s of course not gonna work.But if the scope is much, much smaller, say, 5 minutes of designand then 10 minutes of implementation… then that´s perfectly ok.The solution thus lies in ever smaller “waterfall iterations”. And –as always in life – it helps to be humble. If you devise a solutiondesign don´t deem it above new insights. Always be prepared torevise it.

Which bringsme back to Justin: I haven´t seen any TDDdemonstra-tion where 5 or 10 minutes of “design thinking” have been appliedbefore coding. That´s sad. Because it makes it harder than necessaryto learn to appreciate the power TDD can have. It´s a great tool –if not taken as the only one to come up with designs.

Page 10: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively DescendingTest-Driven DevelopmentAided by Thinking“Hey, Ron, wanna try something new”, Janine asked across the tablein their team room. Ron looked at her uneasily over his line ofmonitors. For hours he had been trying to fix this elusive bug.

“Nah, not now. I really need to get this done first, Jan.”

“Oh, come on, Ron, that´s what you´re telling us all the time.”

Ron blushed. That certainly wasn´t true. Especially not with regardto Janine.

“You know me better than that, Jan. I´m always willing to help youout and stuff. But right now…”

“It won´t take long, Ron. Promised. It´s just so cool. You´ll like it.And… maybe it even helps you with your current problem. Whoknows…” Janine winked at him – and of course Ron´s resolution tonot again get distracted by her crumbled. He sighed and rolled hischair next to her.

“Ok, what´s it? You better make it quick, Jan – and exciting.”

Janine beamed at him. Then with a secretive look and a hushedvoice she said: “I found a better way to approach coding. We´vebeen doing TDD, right. We´ve tried hard to do it right, to do it bythe book.”

Ron nodded slowly. What was she trying to get at? For the pastcouple of weeks they had run coding dojos with their team to getup to speed with TDD. Finally. He strongly hoped she wouldn´t

Page 11: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively Descending Test-Driven Development Aided by Thinking 8

suggest to deviate from that course. It had been difficult enough toconvince their colleagues to at least try automated tests. Those guyswere old code cowboys and not so happy to be asked to learn newtricks.

“Oh, Ron, don´t give me this skeptical look again. Please. It´snot what you might think. TDD is cool – but we can do evenbetter. Remember how we had a hard time doing the kata RomanNumerals? We tried hard, we moved along in tiny steps – but in theend of our timebox we had not finished the task.”

Yes, he remembered that particular coding dojo very well. Theircolleagues had been very frustrated.

“Sure. But our retrospective made clear what we´d done wrong,didn´t it? It was a matter of wrong test priorization.”

“That´s right, Ron. But why did we get the test prios wrong? Again,that is. Because we didn´t give it much thought. Because we did notthink about the solution first. We were so eager to get coding…”

“Well, only in code lies truth, Jan. You know that.”

“True, Ron, true. In the end at least. But what code to write? Whereshould the code containing all the truth come from? How do wetransform a test case into code?”

Ron stared at her blankly. What was this? A lesson in philosophy?Programming is about detail. Code represents all those details.Details need deep technological knowledge. Without solid crafts-manship no running code would get to their customers.

“Come on, Jan. Don´t play this kind of game with me. You know Ihate it. Just tell me what you want to tell me.”

Janine sighed. Usually Ron was very pleasant to work with. A guywho liked to explore the unknown like she did. But sometimes…She took a deep breath, turned to her monitors and pointed to a C#file.

Page 12: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively Descending Test-Driven Development Aided by Thinking 9

“Ok, Ron, see those test cases? It´s the kata Word Wrap. We didit a while ago. Tried to do it like we saw it on the web in RobertC. Martin´s blog⁵. And then – you remember? – George came upwith this additional test case. And our solution did not handle itcorrectly. Neither did Martin´s show case solution.”

Ron nodded. That had been one of the more successful coding dojos– well, until they found out, TDD had not led them to a bug freesolution right away.

“I have pondered long about why in the end we failed. And I guessI´ve found the root cause. We did everything right TDD-wise. Butwe did not enough thinking upfront.”

“What?We should think more ahead? Big design up-front, Jan? Youcan´t be serious. Our retrospective clearly showed we just failed tocome up with the additional test case. Had we added it to our listwe surely would have also solved that problem.”

“Yeah, you´re right, Ron. But how can we think about test cases inthe first place if we don´t have a clue about our solution? Test casesnot only depend on the customer, but also on how we design thecode.”

“Yes, the design naturally flows from the test cases and is refinedthrough refactoring.”

“Ron, just listen to what you´re saying. I know, this is how we´vethought so far. But can this be true? How can code flow from testcases? Code, and its design are the result of our thinking. We plancode before we write it. Maybe we´re not aware of it, but there´s noother way. It is born in our heads. Before we code. The questionsare just: When? And how explicitly?”

He took a deep and somewhat resentful breath – but before he couldretort, Janine drew him back to the code.

⁵http://thecleancoder.blogspot.de/2010/10/craftsman-62-dark-path.html

Page 13: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively Descending Test-Driven Development Aided by Thinking 10

“I know, this sounds theoretical and somehow against what we´veread about TDD and stuff. So let me show what I did. _I read a blogpost about an alternative approach to test-first programming_andtried the suggestions out. Just follow me for a couple of minutes,will you?”

Ron gnashed his teeth, but kept silent and noded.

“Ok, thanks, Ron, honey.”, Janine said and smiled at him disarm-ingly. “I want to do the kata Word Wrap with you in a differentway. These acceptance tests are our starting point. Currently theyare all red. Of course. The Wrap() method just throws a NotImple-mentedException. I want to flesh out its implementation togetherwith you.”

“It´s all the canonical unit test cases – including the one whichbrought our prior implementation to its knees. And two more testcases with real texts. Just for the fun of it. Now, what I want to dodifferently is: I want to think about our solution approach first.”

“What do you mean by ‘thinking’? Do you want me to draw an

Page 14: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively Descending Test-Driven Development Aided by Thinking 11

UML diagram, or what?”

“No, no, Ron. No UML. You know I hate that, too. I mean, well,just ‘thinking’ or talking about how we would accomplish the wordwrapping task by hand.”

“By hand? We need to code, Jan.”

“Yes. In the end we need to code. But software always does what weas humans could do by hand or in our heads. Just much faster. It´sthe non-functional requirements software is written for. Functionalrequirements can always be fulfilled without software – givenenough time and money.”

“You mean, functionality is not important?”, Ron exclaimed indisbelief.

“No, of course. It´s essential. But… Oh, no, let´s no digress. We cantalk about that later. Let´s focus on the kata for now. How could wedo ‘wrapping words’ by hand?”

Ron stared blankly at her. After a short pause Janine took a piece ofpaper and a pencil and wrote:

1. Split text into words

2. Build lines from words

“How about that, Ron? Wouldn´t that very simply describe howword wrapping could be done?”

“Hm… yeah, sure. But that´s not code. It´s just words. You don´tknow if this is actually working.”

“Oh, Ron… Of course this is just words. But those words can betranslated into code, can´t they?We do that all the time. Look here.”

Page 15: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively Descending Test-Driven Development Aided by Thinking 12

“This is not just words, it´s even bubbles, Ron. I know, they don´tcrash. But still it´s a representation of our code. It´s like a little plan:We intend to write a functional unit which transforms an incomingtext into an outgoing text with line breaks. It´s like a map of ourcode. It´s not the code itself, just an abstract view. The same is truefor what I´ve written above. It can be depicted like this.”

“I just refined the first functional unit. The finer grained functionalunits describe how the mission of the coarse grained unit can beaccomplished. You know how to transform the coarse grained unitinto code – you define a function. So why not do the same with thefiner grained units?”

“What do you want me to do, Jan? Write three functions without atest? Is that your new shiny road to reliable code?”

“No, Ron, not that quickly. First I want you to see that thinkingbrought us closer to the solution. Instead of a big problem, we´vetwo smaller problems. And we have a simple hypothesis: if therewas a function ‘split lines into words’ which did what´s suggestedby its name, and there was a second function ‘build lines fromwords’ which did what its name suggested, then their combinationwould solve the word wrap problem. Yes, it´s just a thought. But

Page 16: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively Descending Test-Driven Development Aided by Thinking 13

one that can easily be verified. By code. Give it a try. Write a simplefailing test for theWrap() function. I´ll then take over and show youwhat I mean.”

At the prospect of writing code Ron relaxed visibly. He gentlypushed aside Janine on her chair and grabbed her keyboard. In notime he set up the following code:

“Thanks, Ron. I see you´re cutting right to the chase. You´re right,we don´t want to waste our time on unenlightening trivialities liketests for null or empty strings. Now let me show you how I wantto turn this test to green. Currently it´s failing because there is nosolution code behind the Wrap()-facade. Let´s change that first.”

Janine took over the keyboard and fleshed out the Wrapper classlike this:

Page 17: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Recursively Descending Test-Driven Development Aided by Thinking 14

Continue…

…reading in the book. You can buy it online at leanpub.com⁶.

⁶https://leanpub.com/informedTDD

Page 18: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Using Mocks to Allow forTrue Stepwise RefinementIn my previous article I described a process of designing andimplementing software. It combined TDD with explicit thinkingbefore coding. The dialog I embedded it in was supposed to makethis deviation from traditional descriptions of TDD more palatable.This came at a price, though. The systematic behind this approachwas somewhat hidden. This article is supposed to make up for that.I want to make it crystal clear how I think the process of solvingproblems with code should look like.

“Traditional” TDD

But first a recapitulation of how TDD “traditionally” is depicted.I´m not saying this is how its inventor(s) thought it should be done.Whatever they had in mind, though, got reduced to this:

For a given functional unit of production code you write a test.It´s red/failing first. Then you do the simplest possible thing inproduction code to change it to green/passing. Finally you refactor.

Page 19: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Using Mocks to Allow for True Stepwise Refinement 16

Sounds simple. And it is simple – technically. The hard part of TDDis in the, well, details. Or in the cracks between these steps.

Question number #1: Where do the test cases come from? From thecustomer? Hardly at the level of detail that´s needed to drive out asolution from the inital ignorance. The customer of course shouldprovide acceptance test cases. But they are coarse grained. What´sneeded to refine the solution in small steps are fine grained testcases. And they should be in a certain order so that the solutioncode really can become progressively more complicted.

So where do those nicely prioritized fine grained test cases comefrom? That´s rarely explained in the TDD literature. Authors try toderive them from the problem itself ormaybe from some acceptancetest cases. But never have I seen test cases being linked to thesolution. The reason for that is simple: the solution is supposed tosomehow emerge.

You write a failing test, then switch to the production code side, andthere you just do the simplest thing possible. Solution follows testcase. That´s the “traditonal” TDD mantra.

Unfortunately I´ve seen many, many developers fail at that. Theymake quick progress – with obvious and trivial test cases, so called“degenerate test cases”. And then they hit a wall.

Try this for yourself with the famous Roman Numerals code kata.It´s about a function (e.g. string ToRoman(int number)) to convertarabic numbers like 5, 19 or 42 into roman numbers: V, XIX, XLII.

How does your list of test cases look like?

Let me speculate: 0, 1/I, 2/II, 6/VI, 4/IV, 9/IX, 40/XL, …

First the degenerate test case: 0. Because there is no zero in theroman number system. You need to check for this input, though.Don´t you? That´s good defensive coding practice.

Then the simplest roman number: I. It consist of just a singlecharacter.

Page 20: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Using Mocks to Allow for True Stepwise Refinement 17

Then a sequence of the same character/number. A sequence of likevalues is “higher order” than a single value.

Then a sequence of different characters/numbers. A sequence ofdifferent values is “higher order” than a sequence of like values.

And now for the fun part: the first of those pesky numbers with“reversed digits”. Usually “larger” roman digits precede “smaller”ones like in XVI. But some numbers require for a reversal of thisorder like in IV or IX or XL.

Given the premise “solution flows from test case” this would be aperfectly reasonable order and granularity of test cases. At leastthat´s what I´ve seen many times. And you can find it in theliterature, too.

In reality, though, – as is often the case compared to technicalor recreational literature – things work out differently. And so ithappens more often than not, that developers doing the RomanNumerals kata like this to exercise their TDD skills fail. They donot arrive at a working solution in a moderate time frame of, say,60 minutes.

Of course several excuses are readily at hand. I´ve read and heardoften for example “We wanted to have fun. So we did not reallyfocus on a solution.” or “We wanted to focus on the red-green-refactor steps. A working solution is not that important.”

That´s all nice and well. I don´t want to deprice anybody of his orher fun with TDD or at their dev community gathering. Also I fullyunderstand that in order to learn A you sometimes need to sacrificeB and C for a while. Otherwise you can´t fully focus on doing Aright. In the end, though, that means in your daily work practice, A+ B + C must come together.

But, hey, come on. What are we talking about here? Roman Nu-merals is a trivial problem. It´s orders of magnitude simpler thananything you´re doing for profit. It´s like drawing a stick figurecompared to the Mona Lisa.

Page 21: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Using Mocks to Allow for True Stepwise Refinement 18

No, I don´t buy “focussing on the TDD steps” as an excuse for notsolving a trivial problem in an expanded timeframe like 60 or even90 minutes. That´s inacceptable for any method. And it neglects theneed for closure. Developers want closure. Theywant to accomplishsomething, that means they crave for building something thatworks. Failing to satisfy this need hampers any learning.

And finally: Even if working solutions are produced, I rarely haveseen any which really have lived up to the full TDD processconsisting of three steps. The refactoring step often is skippedaltogether. “We can refactor later. First let´s get this baby off theground. We need working code.”

Most TDD solution on the internet don´t show any sign of refac-toring. Their design is… well, “as usual”.

If you think about this for a minute, this is very plausible for tworeasons. Firstly, closure is reached if the functionality is imple-mented. Clean code is not needed. Secondly, where should a gooddesign come from? TDD does not contain any hints on good design.It just commands: “Thou shalt refactor once the test passes.” But asis with most of such commandments, they are overheard in favorof some seemingly more important issue.

And since rules for good design are orthogonal to TDD, refactoringis neglected except for fairly trivial cases.

Please get me right: I´m not against TDD. Red+green+refactor aregreat – if they only produced the results the claimed on a satisfyingscale.

So this is why I´m looking for a different approach. Can the“traditional” TDD approach be improved. And I think it can. Oneway to improve it has been described by Keith Braithwraite as“TDD as if you meant it”. It improves on the refactoring step. Withit refactoring becomes inevitable. Great!

Another way to improve the TDD rhythm is by thinking beforecoding:

Page 22: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Using Mocks to Allow for True Stepwise Refinement 19

Informed TDD (ITDD)

My experience is, software development becomes easier if we thinkbefore coding. Sounds trivial. Sounds like something everyone´sdoing already. But I beg to differ.

We´re far to quick to grad our keyboards and start coding. The lackof working code for the “stick figure problem” Roman Numeralsafter 60 minutes to me is proof to that. If experienced developersare unable to code a solution – with or without TDD – in thattimeframe, then something is wrong.

What´s missing is not good will, motivation, technical skill. It´sexperience in conceptualizing solutions. Systematically thinkingproblems through to arrive at solutions or at least reasonable(rough) ideas of solutions is an art not valued – at least in manydeveloper circles I´ve attended in the past years.

Everybody is trying his/her best. Of course! There is no lack ofmotivation. However, the hard work put into software developmentsometimes resembles a prison inmate trying to dig his way out withhis bare hands. It would be much easier for him had he a pick ax,or even some explosives at his disposal. Or better: a key. Or evenbetter: not be in prison in the first place.

But to someone sitting in a whole these don´t seem to be options.That´s why we need an explicit emphasize on thinking. We needpreventive measures. Before developers convict “the crime of pre-mature coding”.

For this article I want to call what I´m trying to bring across“Informed TDD”. This is to underline the value of TDD – whileat the same time adding a missing piece, namely information.Information about the solution to be coded.

Ok, here´s how Informed TDD (ITDD) differs from TraditionalTDD (TTDD).

Page 23: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Using Mocks to Allow for True Stepwise Refinement 20

Continue…

…reading in the book. You can buy it online at leanpub.com⁷.

⁷https://leanpub.com/informedTDD

Page 24: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

Release Notes• Current release:

– Added kata “Bowling Game”• 8.6.2014: Initial release

Page 25: Informed Test-Driven Developmentsamples.leanpub.com/informedTDD-sample.pdf · TheSelf-SimilarSoftwareDevelopmentProcess 3 Architects don´t build, they design. That means they think

About the Author

Ralf Westphal is a freelance consultant, project coach, trainer,author, and speaker on software architectural topics and teamorganization.

He is the co-founder of the “Clean Code Developer” initiative toincrease software quality.

Ralf is based in Hamburg, Germany.

• Homepage (de): One Man Think Tank⁸• Email: [email protected]⁹• Twitter: @ralfw¹⁰• Blog (de): One Man Think Tank¹¹• Blog (en): The Architect ´s Napkin¹²

⁸http://ralfw.de⁹mailto:[email protected]¹⁰https://twitter.com/ralfw¹¹http://blog.ralfw.de¹²http://geekswithblogs.net/thearchitectsnapkin