IntelliJ IDEA 8 Refactorings: Remove Middleman

IntelliJ IDEA 8 can help you maintain and improve the source code in a wide variety of ways. For example, to make it clearer, simpler and less knotty, you can use its rich set of refactorings. In this article we’re going to explain the Remove Middleman refactoring, which is helpful when you have classes doing too much simple delegation. Remove Middleman refactoring replaces all calls to delegating methods with the equivalent direct calls.

Class Foo before refactoring
Class Bar
Class Client before refactoring

Here, bar field in the Foo class is nothing more than a simple delegation, so we can safely remove it. Right-click this field and select Refactor | Remove Middleman. IntelliJ IDEA suggests to inline methods which simply forward the calls to this field and remove their declarations. That’s OK for this case, so we click Refactor and enjoy the result!

CLass Foo after refactoring
Class Bar
Class Client after refactoring

If you need the delegating method declarations for backward compatibility, or any other reason, you keep them – IntelliJ IDEA gives you this option.

This entry was posted in Tips & Tricks. Bookmark the permalink.

2 Responses to IntelliJ IDEA 8 Refactorings: Remove Middleman

  1. dlorde says:

    I may have missed something here, or maybe it’s not a good example, but doesn’t this break the encapsulation of bar in class Foo, and prevent a change of implementation of getImpValue() in Foo – the very things forwarding methods are encouraged for?

    Why would I want to do that?

  2. John says:

    Like all refactoring, it applies in some contexts only. Sometimes, the delegation is a result of a change that is no longer relevant and the encapsulation is just a convolution because the client already knows about the delegatee (Bar in this case).

    Perhaps the example would be clearer if class Bar were public.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">