October 17, 2017
Manual Refactoring : Convert Static Method To Instance MethodIn the previous post, I demonstrated how to introduce dependency injection to make a hard-coded dependency swappable.
This relies on the method(s) our client wants to invoke being instance methods. But what if they're not? Before we can introduce dependency injection, we may need to convert a static method (or a function) to an instance method.
Consider this Ruby example. What's stopping us from stubbing video ratings is that we're getting them via a static fetchRatings() method.
Converting it to an instance method - from where we can refactor to dependency inject - is straightforward, and requires two steps.
1. Find and replace ImdbRatings.fetchRating( with ImdbRatings.new().fetchRating( whereever the static method is called.
2. Change the declaration of fetchRating() to make it an instance method. (In Ruby, static method names are preceded by self. - which strikes me as rather counterintuitive, but there you go.)
NOW RUN THE TESTS!
If fetchRating() was just a function (for those of us working in languages that support them), we'd have to do a little more.
1. Find and replace fetchRating( with ImdbRatings.new().fetchRating( wherever that function is called.
2. Surround the declaration of fetchRating() with a declaring class ImdbRatings, making it an instance method.
(AND RUN THE TESTS!)
Now, for completeness, it woul make sense to demonstrate how to convert an instance method back into a static method or function. But, you know what? I'm not going to.
When I think about refactoring, I'm thinking about solving code maintainability issues, and I can't think of a single maintainability issue that's solved by introducing non-swappable dependencies.
When folk protest "Oh, but if the method's stateless, shouldn't we make it static by default?" I'm afraid I disagree. That's kind of missing the whole point. Swappability is the key to managing dependencies, so I preserve that by default.
And anyway, I'm sure you can figure out how to do it, if you absolutely insist ;)
Posted 2 years, 6 months ago on October 17, 2017