Ripeness for Refactoring
People don't refactor nearly enough in most projects. It’s easy to find large classes and methods, inscrutable logic and poor naming in most code bases. When we have that sort of situation it’s easy to just look the code and say “that needs refactoring.” The implication is that we should fix problems when we see them - if we can identify a code smell then it’s time to act. I don’t think that we alway should. Sometimes it’s important to hang back a bit.
The key indicator is when you look at a piece of code and realize that you can refactor it in more than one way and none of them seem like the best approach. The most typical case is a long method. You may see several ways of slicing and dicing it but none of them seem compelling - they emphasize different ways you could choose to ‘see’ your code. In one case it could be as series of sequential steps that solve a problem, in another it could be as a delegation to a new concept, a new class that does the work for you.
If you are uncertain, you have a good reason to pause.
Another case that I see often is a class with several responsibilities one of which is structurally cohesive - you don’t have to break too may dependencies to extract it. You could immediately extract that code as a new class but what should you do if you can’t think of a good name for it? Maybe the best thing is to have a discussion with your team about it and if no one comes up with a compelling name. If you can’t, make note of it, skip the refactoring and move on.
This might sound dangerous - like a recipe for creating an unmanageable code base, but it’s really question of maturity. Everyone involved has to know that the problem in the code is real and that it has to be addressed eventually. They also need to know and appreciate that there needs to be a tipping point - a point past which something has to be done or else the problem will become much harder to deal with. Sad to say, sometimes you just have to pick a path and follow it. It’s just tough to know when you need to do that.
Most of us have enough experience to know when something has become unmanageable. The trick is to unwind that mentally and see the sequence of events right before that. Maybe it’s the switch statement with three cases. You know that if someone adds a fourth or a fifth it will be tougher to refactor. Maybe it’s the use of some library. You’re using it directly in a few places and you know that if you do much more of that you should probably wrap your use to keep the details from leaking into your code and complicating it too much.
There are no hard lines but we can judge the ripeness of various parts of code for refactoring. It’s an important skill.
Join the conversation on Hacker News: https://news.ycombinator.com/item?id=7460015