Putting TDD in practice
I have been learning new concepts about programming and best practices: TDD, SOLID principles, refactoring… among others, during the last couple of weeks.
For my Tic-tac-toe, I have challenged myself to apply them to my code, introducing them when necessary and over time (I don’t recommend to introduce them all at once, it might be a chaos when you starting).
I thought it might be interesting if I write a reflexion on how I am currently doing it.
I started using Test Driven Development to create my tic-tac-toe nearly a month ago now and I find that using that technique has helped me to:
- Stay focused on what I want to develop.
- Write clean code that works!
Stay focused on what I want to develop
I still find very challenging having to write tests before writing any code, as it is very difficult to write about something that hasn’t been created yet!
Said that, I tried my best to do it and it has influenced the way I develop in a very positive way.
I find that it makes me think before I start writing any code (always good) and that it keeps my mind off thinking as a whole, focusing more in a particular thing, what I want to achieve with that test.
TDD has helped me to write simple tests and to test only one thing in each test.
Write clean code that works!
Personally, this is one of the most satisfying things of developing.
Following the TDD rules, after creating a test and making it pass, you would need to refactor your code.
Refractor is a necessity, as for making the test pass, your code might look very messy (which at that stage it’s what you want), and might also have a lot of repetition, constants or your methods might be too complex.
In order to clean your code, you could start by simplifying your methods.
I like to have simple methods because it makes them easier to understand, read, change or fix. If a method is long and complex is likely doing too much, best thing to do it is to extract code in different methods, and have different tests for each one. Ideally each method should only be responsible of doing one thing.
Extraction is also a good way to avoid repetition. If your code is repeated more than twice, best practice is to extract it into a method and call it whenever you need it.
I regularly use constants or hard-coded values to make tests pass, but when refactoring, they are the first thing I need to change. Having them in your code makes it very hard to change or adapt to new changes, the simplest thing to do is to declare variables with the value needed and use them throughout the code. It is easier to change them as the value is only defined once.
There are more benefits I am getting using this methodology but these are the ones that I have noticed have had a bigger impact when I am developing.
I hope to keep learning more about new concepts, reading books, blogs and getting feedback as it is a good way to improve my code.