.st0{fill:#FFFFFF;}

TDD Kata: How to Level Up Your Test-Driven Swift 

 October 5, 2020

by  Jon Reid

How can you learn and practice test-driven development (TDD)? I can explain the principles of TDD. But the question that comes back is, “But what do I actually do in Xcode?”

That’s what code katas are for. They’re not tutorials. They’re exercises, designed to help you grow in your technical agility. I’ll introduce you to some that are specifically for Swift programmers. Then try doing one today!

What’s a Code Kata?

How do professional athletes stay on top of their game? They practice. How about professional musicians? Practice, practice, practice.

Musician practicing at laptop

“Kata” is a Japanese martial arts term for choreographed patterns of movement. They’re also called “forms.” Both beginners and masters practice these detailed patterns over and over. The movements eventually come without thought, because your body knows what to do.

A “code kata” applies this idea to coding. It’s a self-contained exercise you can repeat. Every time you repeat it, you’ll learn something new. At first, you’ll learn one approach to solving a problem. As you repeat the same approach, your learning will shift toward muscle memory.

TDD katas in Swift: At first, you’ll learn one approach to solving a problem. As you repeat the same approach, your learning will shift toward muscle memory.

Click to Tweet

Then you can tackle the same problem but with different approaches. A common style during the annual Global Day of Coderetreat is to repeat a problem while adding different coding constraints. For example, can you code without your mouse? Can you code without exposing properties? How about no conditionals? …A physical analogy would be running with extra weights, or fighting with one hand.

Doing self-contained exercises like this is the best way to practice coding. They’re outside of your production code, so there’s no worry of breaking anything. You’ll throw away what you try because you’re going to repeat the coding kata later. The goal is to gain mastery over coding tools and techniques.

Practice.

So let’s look at some exercises for Swift programmers. But first, here are a few pro tips.

TDD Kata Pro Tips

Use a Scratchpad

Before you start: Make sure you have a piece of paper and something to write with. An index card or sticky note is all the space you need.

Why? Because TDD is a discipline of doing one thing at a time. When you notice something to clean up, don’t dive straight into it. Write it down for later, and stay focused on whatever you’re working on now.

When you complete a task, revisit your list. Clean up the code, and cross the entries off your list.

In the Bowling Game example, this scratchpad is actually shown in the slides. In the upper-left corners, you’ll see boxes like this:

Game creation is duplicated / roll loop is duplicated

When you see this, write it down on your scratchpad. I mean it: write it down. This will help reinforce good TDD habits.

Daily Practice

When you’re working on a new code kata, I’d recommend going through the entire exercise, once through.

Then we can follow Marlena Compton’s advice in Learning TDD with Exercises, by doing 15 minutes a day. Set a timer. Stop when you get to 15 minutes. The next day, continue from where you stopped. Try making it a small part of your daily routine.

Use Templates

Apple fills its Xcode templates with useless cruft. They also fail to add other things that would actually help. Try using my test file templates and test-oriented code snippets.

Custom test templates from Quality Coding

In the spirit of using different constraints, work through a TDD kata without them. Then do it again, using my templates. See if they change the experience.

TDD Katas in Swift

Bowling Game

The idea is to score a game of bowling. Follow along with slides:

In my version of the Bowling Game slides, green lines show code that we just added. Red lines show code that we’re about to remove. For example, here we added the last line, and are about two remove the two lines above it:

Code with red and green colored gutters

Let me call out some specific slides…

Slide 12: Set up Xcode to show test code and production code side-by-side, mimicking the slide. Do this as follows:

  • Swift: Click the test file so it shows on the left. Option-click the implementation file so it shows on the right.
  • Objective-C: Click the test file so it shows on the left. Option-click the .h file so it shows on the right. Shift-option-click the .m file and double-click the “+” in the bottom right. On the right side, you should have .h above and .m below.

You may prefer to use tabs instead, and that’s fine. The goal is to see the code side-by-side, or switch between them so fast that it doesn’t matter.

Slide 23: Select the two circled lines, then use the context menu to Refactor → Extract. (If Xcode refuses, do it by hand. Or, try AppCode which has better automated refactoring.)

Slide 40: You have various options to rename loop variable “i” using Xcode:

  • Do it by hand.
  • Use “Refactor → Rename” observing how long it takes to index and animate.
  • Select its first appearance and do Edit All in Scope. This is available through the menus, or in a pop-up menu that appears when you hover over a selection, as shown here:
Edit All in Scope

Try each option to see how they affect your “flow.” And one more option is to try AppCode.

Gilded Rose

https://github.com/emilybache/GildedRose-Refactoring-Kata

Not a TDD kata, this is a legacy code refactoring kata. You start with a glob of untested code. Your challenge:

  • First, bring the code under test.
  • Clean it up. The goal is to make it easy to make the change below. Can you move in small, verified steps?
  • Then add a new feature: “Conjured” items should degrade in Quality twice as fast as normal items.

Name Normalizer

https://github.com/jlangr/name-normalizer

The challenge is to input a name in standard English order, returning the name normalized for use in a bibliography.

This is a “TDD paint by numbers” exercise: the tests are written for you. Initially, they’re all disabled. Enable them one-by-one, and follow the remaining two steps of the TDD Waltz:

  • Write enough production code to pass the test.
  • Refactor the code so it expresses the domain. (In this exercise, leave the test code alone.)

This kata is available in several languages, including Swift. If you check out the swift-solution branch, you can follow one possible solution as a series of commits.

I also offer 75-minute mob programming sessions in this exercise on PubMob.

Time-of-Day Greeter

I offer this kata in the last chapter of my book, iOS Unit Testing by Example.

Make code to greet someone by name, according to the time of day:

  • 5:00 am – 11:59 am: Good morning.
  • 12:00 pm – 4:59 pm: Good afternoon.
  • 5:00 pm – 4:59 am: Good evening.

So if we provide the name “Lauren” and the time is 4:15 p.m., it should return, “Good afternoon, Lauren.” Allow for the possibility that there is no name.

Do you have other TDD katas in Swift that you like? Let me know, and I’ll add them to the list.

__CONFIG_colors_palette__{"active_palette":0,"config":{"colors":{"62516":{"name":"Main Accent","parent":-1}},"gradients":[]},"palettes":[{"name":"Default Palette","value":{"colors":{"62516":{"val":"var(--tcb-skin-color-0)"}},"gradients":[]},"original":{"colors":{"62516":{"val":"rgb(19, 114, 211)","hsl":{"h":210,"s":0.83,"l":0.45}}},"gradients":[]}}]}__CONFIG_colors_palette__
__CONFIG_colors_palette__{"active_palette":0,"config":{"colors":{"49806":{"name":"Main Accent","parent":-1},"3a0f6":{"name":"Accent Light","parent":"49806","lock":{"saturation":1,"lightness":1}}},"gradients":[]},"palettes":[{"name":"Default","value":{"colors":{"49806":{"val":"var(--tcb-skin-color-0)"},"3a0f6":{"val":"rgb(238, 242, 247)","hsl_parent_dependency":{"h":209,"l":0.95,"s":0.36}}},"gradients":[]},"original":{"colors":{"49806":{"val":"rgb(19, 114, 211)","hsl":{"h":210,"s":0.83,"l":0.45,"a":1}},"3a0f6":{"val":"rgb(240, 244, 248)","hsl_parent_dependency":{"h":209,"s":0.36,"l":0.95,"a":1}}},"gradients":[]}}]}__CONFIG_colors_palette__
Previous
__CONFIG_colors_palette__{"active_palette":0,"config":{"colors":{"49806":{"name":"Main Accent","parent":-1},"3a0f6":{"name":"Accent Light","parent":"49806","lock":{"saturation":1,"lightness":1}}},"gradients":[]},"palettes":[{"name":"Default","value":{"colors":{"49806":{"val":"var(--tcb-skin-color-0)"},"3a0f6":{"val":"rgb(238, 242, 247)","hsl_parent_dependency":{"h":209,"l":0.95,"s":0.36}}},"gradients":[]},"original":{"colors":{"49806":{"val":"rgb(19, 114, 211)","hsl":{"h":210,"s":0.83,"l":0.45,"a":1}},"3a0f6":{"val":"rgb(240, 244, 248)","hsl_parent_dependency":{"h":209,"s":0.36,"l":0.95,"a":1}}},"gradients":[]}}]}__CONFIG_colors_palette__
Next

Jon Reid

About the author

Programming was fun when I was a kid. But working in Silicon Valley, I saw poor code lead to fear, with real human costs. Looking for ways to make my life better, I learned about Extreme Programming, including unit testing, test-driven development (TDD), and refactoring. Programming became fun again! I've now been doing TDD in Apple environments for 19 years. I'm committed to software crafting as a discipline, hoping we can all reach greater effectiveness and joy.

  • Hi Jon,
    I really enjoyed the kata, and I appreciate the work you’ve done to explain the mechanics of doing TDD in Xcode. Also, thanks for making the improved template available.
    On Slide 38, why do you immediately recognize the flaw in the design and refactor it then and there? At that point in the project, the design seems perfectly suitable for the tests that have been written, and a new test (like testOneStrike) would highlight the flaw and force the refactoring.

    • Robert,
      I’ll try to explain Slide 38, but need to back up. testOneSpare was introduced back on Slide 29, as a failing test. In the process of trying to think about what to code to get it to pass, we discovered deficiencies in the design. So we comment out testOneSpare in order to concentrate on refactoring — wearing one hat at a time.
      As of Slide 36, the refactoring has been proved successful. So I re-enable testOneSpare, and run it to see that it’s still a failing test.
      On Slide 38, I’m back at the point of trying to code something that’ll pass testOneSpare. This is the second try. Again, I discover a deficiency in the design. So once again, I switch hats by commenting out the test, concentrating on tweaking the design (refactoring) in a way that doesn’t break the previous tests.
      This illustrates the principle of wearing one hat a time. Either you’re coding to get a new test to pass, or you’re refactoring. But don’t do both at the same time. We’re basically walking on stilts: Lift one, or the other, but not both. :) By keeping one foot grounded, so to speak, we reduce the risk of falling over.
      Does that makes sense?

  • Hello Jon.
    Thanks for great excercise. It’s awesome! I practised it yesterday and have some thoughts:
    – Apple template looks almost like yours now (XCode 5), and it’s easier to use it than run yours (I couldn’t manage it to work – tests wasn’t being run)
    – Last test was successful without any changes in code (code from previous test was enough) – is that ok or I missed something?

    If you want I can send you detailed description what went different than in yours PDF so you can update it for XCode 5.

    Have a nice lecture here in Poland. Sad that I missed opportunity to be there. :(

    Daniel

    • Daniel, I’m glad you found it helpful.
      – Yes, Apple’s latest template finally addresses my concern. You no longer need my template, unless you want to use the older SenTestingKit.
      – The last test is a surprise: it basically shows that there’s nothing left to do! But it’s hard to tell without a test to prove it.

      Polish hospitality is wonderful! I had a great time, and look forward to going back.

  • Hi Jon! I’m just starting this using the Swift version…I noticed on slide 11 it says “Select Objective-C as the language.”, but it should say Swift.

  • I finished going through it and here’s what I noticed could be tightened up, if you want. ;)

    Slide 11

    – It should say “Select Swift as the language” instead of Objective-C. (error)

    Slide 12

    – there is a minus sign in front of fun testGutterGame() that I think is leftover from Obj-C? (error)

    Slide 15

    – the return line in func score() doesn’t need the semicolon (unswifty)

    Slide 20

    – theScore variable doesn’t require “: Int” since it’s implied in Swift (unswifty)

    Slide 27

    – the semicolons in the new test should be removed (unswifty)

    Slide 28

    – the red comment on the bottom should say 16 instead of 20 (error)

    Slide 32

    – rolls variable doesn’t require “: [Int]” since it’s implied in Swift (unswifty)
    – currentRoll doesn’t require “: Int” since it’s implied in Swift (unswifty)
    – currentRoll++ should be changed since it’s deprecated very soon in Swift (deprecated)
    – Change to:
    rolls[currentRoll] = pins
    currentRoll += 1
    – the return of func score() was changed from theScore to score but that line isn’t green

    Slide 47

    – the strikeBonus method has a minus sign in front of private func (i.e. -private func) (error)

  • Hi Jon,

    Thanks for creating these iOS versions of Uncle Bob’s Bowling Game Kata. I’ve just tried the swift one and I noticed that the following line –


    for _ in 1...10 {

    on slide 37 (The Third Test) throws an ‘Index out of range’ exception.

    It should, of course, be


    for _ in 1...9 {

    which is the equivalent of the java code from Uncle Bob –


    for (int frame = 0; frame < 10; frame++) {

    Cheers,

    Paul.

  • You’re right Jon. I’d was accidentally counting the frames from 0 to 10 on my first day

    for _ in 0...10 { // Doh!

    but, as you say, it makes more sense to count the frames from 1 to 10 (rather than 0 to 9).

  • {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
    >