Refactor working code for reuse or duplicate

code-reuserefactoringtechnical-debt

I have always avoided duplicating code regardless of the circumstance. For example, if I have a working piece of functionality that needs to be re-used by different entities, I always refactor to make this functionality available. Under no circumstance would I duplicate code. I am probably a little rigid when it comes to this but I really do not like duplicating code.

I currently had a slight disagreement with our Team Lead who suggested that instead of refactoring, I should copy entire piece of functionality I require into a different class and then we can decide how best to refactor at a later date. This is even after confirming that my previous refactoring efforts did not break any of the unit tests.

I further had this conversation today with my previous manager, and his mentor, who both sided with my Team Lead. Their argument is incurring technical debt is OK, and almost always preferable, especially if you are running into time constraints, which I understand. My counter argument was yes, we do not want to skip deadlines but one must always consider the cost of refactoring and this usually should be the first instinct, especially if we are simply moving functionality into a new location that renders it accessible to all. Proper unit test can also ensure that refactoring efforts do not break existing functionality. Also is it not always better to pay off the debt now rather than later? I can only imagine what this task will entail if all members of the team simply duplicated code.

Suffices to say that we had to agree to disagree. In his book titled Clean Code, Robert Martins emphasis continuous refactor during development so I was surprised by the response of my previous manager.

What are you opinions on this?

Best Answer

If your team lead, previous manager and mentor are all saying that you don't have the time to refactor now because of time constraints, then you don't have time to refactor it now. Note it, stick a TODO in there and refactor it later.

You're not being held responsible for the delivery date. They are. You're probably not aware of what's going on with the bigger picture, and you don't need to explain to the CEO/board why the project is two weeks late. Saying "We wanted to have a cleaner code base now, instead of in a months time, so we're delaying the project, and now your job is on the line" is not a good excuse.

In an ideal world you would always be able to refactor and not incur technical debt. It's always the preferred solution, no-one is arguing that. I too hate duplicate code - I'm actually in the situation now where I've inherited a lot of copy and paste code and it's going to be a nightmare to fix up, but the business did what they needed to do to deliver the project, and they can now afford to spend the extra time to clean up the code.