I have a bastard template method implementation. Rather than being a base class with subclass implementations, it is a static method on a util class that takes an interface to which it delegates. I want to refactor this to the more common pattern so I can stop passing the Domain class around.
The first step I think is turn template into an object method, but then I am at a loss for inspiration as to how to move my 5 Helper implementations (not shown) into subclasses of the new Template object.
public interface Helper
{
void doFirstThing(Domain d);
void doSecondThing(String id);
}
public class UtilClass
{
public static void template(Domain d, Helper h, String who)
{
//begin database transaction
try
{
//some logic
h.doFirstThing(d);
//more computation
h.doSecondThing(d.getId());
//database commit();
}
finally
{
//if transaction open database rollback();
}
}
}
public class Domain
{
public String getId()
{
return "value";
}
}
I thought about it some more and came up with the following steps.
Replace Method with Method Object. Leave the helper out of the constructor arguments. I also skip the part about making local variables fields. The automated refactorings do that so well when I want it done.
Inline the static method.
Make an implementation a subclass of the new MethodObject. this involves adding/modifying a/the constructor.
Where the Method Object is created and called with the implementation, just create the implementation and call the template method.
new MethodObject(d, who).template(new Implementation(d, who));
becomes
Implementation impl = new Implementation(d, who);
impl.template(impl);