Clean Code | TDD | Swift | iOS | Quick Notes

TDD is a way of writing software, where we write as little code as possible to make the test pass and then late refactor the code.

Golden laws from Uncle Bob

  • You may not write production code until you have written a failing unit test.
  • You may not write more of a unit test that is sufficient to fail and not comping is failing.
  • You may not write more production code that is sufficient to pass the currently failing test.

Whenever we create a new iOS app, we start with UI/ViewController/Business Login directly but Idea here is to start with the Test-cases. How? Let’s say you want to add the functionality to find out the divisible or not as below mentioned the code. Write down the test-case first.

func testIsDivisibleByThree() {
let brain = Brain()  
let result = brain.isDivisibleByFive(number: 5)
XCTAssertEqual(result, true)
}

But we don’t have the class Brain till now!!! So create a class adds the function, don’t forget the aim is to write as minimum code as you can.

class Brain {
    func isDivisibleByThree(number: Int) -> Bool {
        return true
    }
}

Because as of now, we are returning static boolean value, test-case will be a pass for sure. Same pattern we need to follow for each and every code we are going to write.

Simple words I can say there are 4 stages in TDD.

RED – Write down the test case
GREEN – Write just enough code to make the test-case pass
REFACTOR – Clean up existing code
REPEAT – repeat the cycle

In above codebase we have done RED and GREEN, let consider the stage 3rd, REFACTOR.

Let’s say now we have to write a function where we need to check whether a number is divisible by given number or not, like this

func isDivisibleBy(divisor: Int, number: Int) -> Bool {
  return number % divisor == 0
}

So we have refactored the code, Utilizing it like.

func isDivisibleByThree(number: Int) -> Bool {
    return isDivisibleBy(divisor:3, number:number)
 }

the idea is to repeat these steps so we can make sure when we are making any new changes, is it breaking some existing functionality.

I have tried to create short notes on how to follow TDD but also Idea is here is to decouple your code from UIViewController as much as possible so that it will give you more testability scope (for implementing this I have tried MVVM design pattern in few my recent projects, will share one quick notes on that as well).

Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.