http://www.perlmonks.org?node_id=629156

You are using a temporary variable to hold the results of an expression.

Extract the expression into a method. Replace all references to the temp with the new method. The new method can then be used in other methods.

(Fowler, p. 120)

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:

sub get_price{ my $self = shift; my $base_price = $self->{_quantity} * $self->{_item_price}; my $discount_factor = $base_price > 1000 ? 0.95 : 0.98; return $base_price * $discount_factor; }

becomes:

sub get_price{ my $self = shift; return $self->base_price() * $self->discount_factor(); } sub base_price{ my $self = shift; return $self->{_quantity} * $self->{_item_price}; } sub discount_factor{ my $self = shift; return $self->base_price > 1000 ? 0.95 : 0.98; }

Get the code

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.

perl -e 'split//,q{john hurl, pest caretaker}and(map{print @_[$_]}(joi +n(q{},map{sprintf(qq{%010u},$_)}(2**2*307*4993,5*101*641*5261,7*59*79 +*36997,13*17*71*45131,3**2*67*89*167*181))=~/\d{2}/g));'