I’ve heard it said that every interesting question in software engineering has an answer that says, “It depends”. What I’ve realized recently is that this applies to a lot of questions that I would have normally considered uninteresting. Because of this, it’s taken me longer than it should have to see that past solutions to problems aren’t working.
For example, a good rule of thumb is that you shouldn’t have to change production code solely to make it more testable. It makes people uneasy to make a private method public just because you’d like to test it. This is usually a smell that there’s a hidden class somewhere or you should write a higher level test, etc.
But, why do we dislike changing production code just to make it testable? Well,
private is a form of documentation. The former says, “There could be some code you can’t see that uses this.” This will slow you down or make you reconsider refactoring the code later. Worse, some other production code could end up calling the new
public method when they really shouldn’t be.
I, like most, take this rule for granted. But, “it depends”. If you’re working in a legacy code base with few tests and lots of Singletons, I have no qualms with putting a
setInstanceFieldForTests method so I can start writing tests. In this context, I gain much more value than I lose by changing the production code solely for testability because it makes the code base easier to understand and refactor. It’s the easiest way to be able to write integration tests around the code that uses the Singleton. But in a green field application, the same action can make the code base more difficult to understand and refactor.
Problems and their solutions rarely exist in a vacuum. There is usually a context where the solutions make sense and a context where they do more harm than good. I find it very difficult to recognize this context. I usually throw it out when I find a good solution to a problem and when I see a similar problem I try to apply it without recognizing how the previous context invalidates the solution in the second case.
I wonder if it’s human nature to be bad in this way or if it’s a skill that one can improve in. I’d like to hear other’s techniques in deciding what to pick when the solution “depends”. I’d also like to hear your stories about situations you’ve experienced where “it depends”.