Working With Existing Code

May 20, 2020    Development

Working With Existing Code

I hope the code you work with is more like ravioli instead of spaghetti. I heard that from John Papa years ago. Most of the code we will work with is already existing. Let’s make it better as we work in it.

"Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code. ...[Therefore,] making it easy to read makes it easier to write." 

Bob Martin in Clean Code

I had a an experience lately that prompted me to write this article. I recently had a bug where I started in on it, then 52 commits later I had broken things. This code wasn’t the best laid out and there were a lot of complicated user interactions. The risk was too great. I realized I had to get the value out of my work, then go back and fix the issue.

It took me a long time to recognize that I needed to do the refactoring earlier.

I ended up making a new branch, cherry-picking and copying in code to a point. Then I added the tests where I should have, then slowly moved the code forward. I made a PR out of that, then went back to fix the bug at hand.

@Omnitech we are going to read Working Effectively With Legacy Code together this summer. Maybe I’ll add more ideas from the book here this summer.

Martin Fowler also has a Refactoring book

Unit and Integration tests

Are there existing tests?

Count yourself blessed. Look for missing code coverage, if none, then refactor with less fear.

Are there 0 or minimal tests?

  • Check existing code coverage and identify the gaps
  • Write tests to cover those gaps before refactoring and changing code
    • These tests should ensure that the functionality is the same

Follow the Boy Scout rule “leave things better then when you first arrived”

  • Make it more readable
  • Extract to smaller methods that don’t need comments
  • Extract to smaller classes
  • Clean up warnings and messages
  • Add comments that tell why something is this way, instead of what it is doing

Take your time

“If you have time to fix it later, you have time to make it right the first time” ~ A co-worker’s mother

Make small and frequent Git commits.

This is extremely important if you find you’ve broken something and need to go back. Writing tests before changing code will help you avoid having to go back.

Pull Request valuable refactoring, sooner rather than later.

Adding new tests and refactoring is creating value. You want other developers to be able to use this as soon as possible and avoid merge conflicts. Writing tests first to maintain the current functionality will give you confidence to check in more often.



comments powered by Disqus

Please consider using Brave and adding me to your payment ledger. Then you won't have to see ads!

Support me and download Brave!

Use Brave