Refactoring: Extract Method to Function

You have a method whose purpose is not cohesive with the containing class. 

Turn the method into a function that can later be moved to a collaborating object or standalone fragment.

For example suppose you had a method that created the rendering output for an API request on a user class -

def to_api_hash
    id: id,
    email: email,
    name: name,
    avatar: get_avatar

(this could as equally be a method that computed a value such as a bill payment or performed a validation). The first step is route the method to another "function method" on the class which takes the instance as an argument and has no references or state other than its inputs.   

def to_api_hash
def to_api_hash_for(user)
    avatar: user.get_avatar

This protects all the class callers and allows you to test the new function in isolation. The next steps are to move the function to its intended destination and update callers away from the domain class. 

See also: Extract MethodMove Method and Replace Method with Method Object.


It's common for younger codebases, especially web based systems, to refactor code out of controllers and views into model or domain classes in order to centralise and organize functionality such as computed business logic, output preparation or validations. As the codebase evolves over time the model can accumulate a large number of methods, resulting in what's sometimes called a "fat model", which then justifies moving code into collaborating objects or service objects. The latter can often be the case when the domain class has functionality that manipulates multiple domain objects such that there's no natural home in the domain model, as it represents an application usecase. 

The domain class may have many callers for these methods. This can be tricky in larger codebases that use generic names in the case of dynamic languages, or are using runtime reflection in statically typed languages - a generic name might be in common use across the codebase. In the case where callers are hard to detect, the option remains to leave the old class method in place as a delegate to allow time to determine the callsites using the old method.

Another reason to extract to functions is establish a 'clean core' where application logic can be more easily maintained and tested independently of framework or database storage concerns, eg as described by Bob Martin in his post 'Clean Architecture'.