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

You have a long method that uses local variables in such a way that you cannot apply Extract Method

Turn the method into its own object so that all the local variables become fields on that object. You can then decompose the method into other methods on the same object.

(Fowler, p. 135)

Here's how it looks:

sub validate{ my $self = shift; my $errors_ref; my $validation_profile = $self->get_validation_profile(); my $input = $self->get_input(); my $result = $self->process_input_against_profile( $input => $validation_profile ); if ( $result->{success} ) { return { success => 1 }; } else { $errors_ref = $self->process_errors( $result ); return { success => 0, errors => $errors_ref, }; } }

becomes

sub validate{ my $self = shift; return Validator->new( $self->get_input )->validate(); } package Validator; sub validate{ my $validator = shift; my $result = $validator->process_input_against_profile(); if ( $result->success() ) { return { success => 1 }; } else { return { success => 0, errors => $result->errors(), }; } }

Get the code

I put together my own example because Fowler's own is contrived and not directly applicable. In his own words:

A proper example of this requires a long chapter, so I'm showing this refactoring for a method that doesn't need it.

Thanks Martin :)

My example may not be the best application of this refactoring pattern either, but I find this to be the most common reason for using this pattern and I think the example is a little more applicable to the context Perl developers are used to working in. In this case, I have a cluttered class representing a Web application that does a lot of work and I have utility methods to help with the validation. I don't really need those in there, so I make a new class to handle the validation and put my methods over there.

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));'