2011/02/10

How to refactor other's code

I was in a position today to refactor some code that didn't belong to me. Without going into much detail I was asked to implement a feature that required some significant changes to some fresh code.

A friend was online at the time. I remembered he had a very gentle way of dealing with other programmers. He happens to be very smart and, as such, was in a position to review/teach most of the people at the company we worked at together. I asked him how to do it:

me:
hey i have a question. how do you refactor someone else's code without being "that jerk who's refactoring my code"? is it possible?
him:
That is very hard. When I approach that issue I always remember a quotation even though I forgot who said it: "To successfully critique something you must first learn to love it."

Also I'm probably rewriting the quote somehow

If you approach someone about refactoring their code and show them that you've taken the time to understand why their code was written the way it was, or, if it's super crappy, why they were in a compressed time schedule while writing it, or why it would help them to work with you to learn it better, etc. etc…. basically if you approach them with respect and compassion, and they get all pissy, at that point it's their fault

But the best thing is to communicate period, often times I've seen people shrink away from communicating because they don't want to confront the other person, and they end up rewriting the code without consulting with the original coder, or, worse, not dealing with the issue and leaving the bad code to rot. Confrontation, even if it pisses the person off, is always better than doing nothing or doing something around the person