-
-
Save jbrains/1259077 to your computer and use it in GitHub Desktop.
Separating use from construction - Before
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BusinessObject { | |
/** @deprecated */ | |
public void actionMethod() { | |
actionMethod(Service.getInstance()); | |
} | |
// A SEAM! A SEAM! New clients should use me!! | |
public void actionMethod(ServiceDelegate serviceDelegate) { | |
// Other things | |
serviceDelegate.doService(); | |
// Other things | |
} | |
// Am I a Service? Am I a Delegate? Can you tell? Do you care? | |
abstract class Service : ServiceDelegate { | |
/** @deprecated Haven't all my clients died yet!? */ | |
public static Service getInstance() { | |
return new ProductionService(new ProductionServiceDelegate()); | |
} | |
public abstract void doService(); | |
} | |
/** @deprecated Depend on ServiceDelegate directly, if you can */ | |
class ProductionService : Service { | |
private final ProductionServiceDelegate delegate; | |
public ProductionService(ProductionServiceDelegate delegate) { | |
this.delegate = delegate; | |
} | |
public void doService() { | |
delegate.doService(); | |
} | |
} | |
// Look how mockable I am! New clients should use me!! | |
interface ServiceDelegate { | |
void doService(); | |
} | |
class ProductionServiceDelegate() { | |
public ProductionServiceDelegate() { | |
// copy from old ProductionService | |
} | |
public void doService() { | |
// copy from old ProductionService | |
} | |
} | |
Step 2: Introduce a mockable interface. https://gist.github.com/1259077/0780c77b0d435233adb1ac302fffdede3634b3b9
Step 3: Add the appropriate instructions for new clients to use new code and old clients to migrate when possible. Hope people read them. https://gist.github.com/1259077/1a9cda66e9a8b7856e6af3dafd9df1080dd11853
Awesome example. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Step 1: Push the implementation down into a new class. https://gist.github.com/1259077/b4a258f66b7a9e95c04e7e62040e38b85b867d33