Refactoring with TDD – “Currency example”

Today, I’ll show a program based on a TDD approach which I explained in a previous article. At the beginning it will have two classes representing two currencies “złoty” and “euro”. I’ll test the multiplication money and compare them like –  one euro is equal to one złoty. And every time I try to refactoring our code – remove duplications.

Currency project

So our test for złoty looks like this:

Red phase is done, so try pass the test in green phase.

Ok. We pass our tests. At this point it’s have nothing to refactoring.

We should add the name of the currency to our class in order to later be able to recognize it more easily.

Test is now red so fix it.

Now it’s everything ok.

So let’s add the Euro currency to our program.

Euro Tests:

Euro Class:

Hmm… ok we pass our test but… Our classes Euro and Zloty it’s almost the same. Something is wrong here, we break the principle DRY.

Writing class representing currency. Copy the whole repetitive code to class Currency and remove this code from our two classes (Zloty and Euro).

Now we can refactor our tests.

We shouldn’t use two Assert on one test but it significantly reduces the length of the post. 😉

Now we have base class that represents all currency. We implement that the class of the Euro and Zloty inherits from Currency.

The question is: “Why do we need variable currency?”. It’s good question we can recognize our currency by class so now we don’t need it. Apply the principle of YANGI.

Refactor it and let’s remove test Check_If_Name_Of_Zloty_Class_Is_PLN_And_Name_Of_Euro_Is_Eur and public variable named currency.

Now let’s valid our classes.

Our tests are now positive and we remove duplication and unnecessary code. Yupi.

But at the end we should check if one euro is equals to one złoty.

Red phase:

Green phase – add method equals to Currency class. Comparing the value of the currency and whether they are of the same class.

After running tests, we see

tests TDD


We did a program that checks if the money is in the same currency. In addition with the methodology TDD thanks to our code looks nice and clear. I hope that You seen, with TDD – refactoring code is much simpler because we have larger trust that something we don’t spoil.

Link to project.

For homework you can write class Cantor which convert our currency 😉 . Test for it:

Have a nice day 😉

One Comment on “Refactoring with TDD – “Currency example””

Leave a Reply

Your email address will not be published. Required fields are marked *