Some software pieces can be harder to maintain than others, Why? and how using TDD can help software engineers avoid legacy code problems?
So we can define legacy code as:
- any complex code without tests.
- any code with bad tests.
How Legacy Code happens?
According to one of Lehmans Laws:
As a system evolves, its complexity increases unless work is done to reduce it.
Legacy code is the result of many people working on the same project, over a long period of time, with conflicting requirements, under time pressure.
Legacy code has no end
It sounds scary to edit legacy and it’s. that’s why we need a safety net to make sure whatever we change we are not changing any behavior. that’s exactly what automated unit tests should do for us.
Why Unit Tests?
So what went wrong here?
Unit Testing: is some extra code separated from your application code, you write that code to test each component in your code as an isolated unit.
If only we had all app functions covered with tests, we would have caught the bug while running tests. A step that should be running before deploying to production, ensuring high-quality fixes.
Alright, so let’s write unit tests, a good way to write tests is TDD.
What is TDD?
Test-Driven Development is a way of development, where you let unit testing drive and impact your development.
- ☂️ write a test for the smallest function you want to implement.
- ▶️ run the test
- ❌ watch the test fails (remember you didn’t write any code yet 🤷♀️)
- ✔️ write the smallest code change to make the test pass
- 🔨 Refactor code
- 🔁 repeat
Why TDD?
That way by the time you finish your feature/project you’ll also finish unit tests, here are some notes about TDD:
- Increase productivity: Although TDD means writing tests which are extra code. which means spending more effort and time which seems like slowing your process. But on the long term TDD increase chances of noticing bugs and code that need to refactor as early as possible which saves time in the long term.
- High-quality code: It was found that TDD reduces bugs by 40–60%.
- It’s More Fun: TDD cycle is like a Reward cycle, It consists of (trigger – action – reward). First, you see your test fails which triggers you to take action and write code to fix it. Then you receive your reward seeing your tests pass. this’s when your dopamine level increases, it just feels great, and you simply get hooked in the cycle.
Conclusion
More on the Topic:
A good book on the topic Working Effectively with Legacy Code
Also, don’t forget to check our post on Quality and Rapid Feedback
Please contact me if you have any thoughts about the topic, and hit share if you like it. 🙏
Thank you for reading. ❤️