(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
to_api_hash_for(self)
end
def to_api_hash_for(user)
{
id: user.id,
email: user.email,
name: user.name,
avatar: user.get_avatar
}
end
This preserves all the classes 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.
It's common for younger codebases, especially web based systems, to refactor code out of controllers into model or domain classes, to centralise 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 (sometimes called a 'fat model') which then justify moving into collaborating objects or service objects. The latter can often be the case when the domain class has functionality that manipulates multiple domain objects that has no natural home in the domain model as it represents an application usecase.
However the domain class may have many callers for these methods, which 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, as a generic name might be common 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 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'.