|Perl: the Markov chain saw
Refactoring Perl #4 - Replace Temp with Queryby agianni (Hermit)
|on Jul 27, 2007 at 17:19 UTC
The following examples follow Fowler's, although I use the ternary operator, as this is a perfect example of when to use it. Here's how the refactoring looks:
Fowler suggests that that this is "often a vital step before Extract Method" (Fowler, p. 120), which is probably when I have found my self using this technique most often -- unwittingly until now.
This particular example seems a little simplistic at first blush. Generally, I find this to be more important when I am trying to refactor one large method into a few smaller methods, each of which needs access to what was once a local variable. Often I have done this by declaring the local variable in the main method and passing it to each of the refactored methods instead of refactoring it as a query method. Sometimes that the only option when working with a procedural programming language, like non-OO Perl.
The need to extract queries in this particular case doesn't seem that strong given the single use of the queries. That said, as I suggested in Inline Method, this example extracts what are essentially business rules for the greater application. In this case, these are rules that are generally referred to as enumerators, defining how discounts are applied and how a total price is calculated. I find that it can be very useful to keep these business rules separate from the logic that defines the behavior of the application itself. I would likely put these extracted queries into their own class for business rules.