I’m a big fan of both refactoring and automation. It’s no wonder, then, that the support for automated refactoring in Eclipse makes me very happy. I find that it makes me a lot more productive, and I produce better code. That’s because performing a refactoring is easy and fast enough to actually do it.
I also find that I refactor routinely. Where Martin Fowler, in his classic book Refactoring, gives the advice not to mix refactoring and adding new functionality, I do it almost mindlessly anyway. No need to run unit tests before and after the refactorings, since I know they Just Work™.
Not so with any refactorings that are not supported by the tool, though. For instance, when trying to adhere to the Law of Demeter, one would want to perform the refactoring Hide Delegate. Unfortunately, Eclipse has no support for this refactoring 😦 You can, however, simulate this refactoring using a combination of other refactorings. Let me explain that using a simple example.
We start with the following abstract code that shows the situation before we want to apply Hide Delegate:
public class Client { public void example() { final Server server = new Server(); server.getDelegate().method(); } } public class Server { private final Delegate delegate = new Delegate(); public Delegate getDelegate() { return delegate; } } public class Delegate { public void method() { // Do it... } }
First, we perform Extract Method on server.getDelegate().method()
(make the method public
):
public class Client { public void example() { final Server server = new Server(); method(server); } public void method(final Server server) { server.getDelegate().method(); } }
Next, perform Move Method to move method()
to Server
:
public class Client { public void example() { final Server server = new Server(); server.method(); } } public class Server { private final Delegate delegate = new Delegate(); public Delegate getDelegate() { return delegate; } public void method() { getDelegate().method(); } }
And, voila, we have performed Hide Delegate!