Java Programming Tip: Creating "Method Bridges" using Public + Default Visibility
In Java, the default visibility for classes, methods, and fields is "package", meaning only code that is in the same package as the code in question can access it. However, sometimes it is useful to create large chunks of logic that need to communicate mainly amongst themselves, but should also be accessible by a limited subset of external code. This can be accomplished using what I call a "method bridge".
Let's imagine you have a few package-visible classes and their package-visible methods:
class Foo1 {
void bar1() {
...
}
}
class Foo2 {
void bar2() {
...
}
}
class Foo3 {
void bar3() {
...
}
void bar4() {
...
}
}
Keep in mind that the basic idea here is that these classes are actually quite tightly-coupled. Perhaps they were originally one large class that has been refactored into several smaller ones, but still maintain a lot of crosstalk. Or perhaps they are simply such specific types of logic that there is just no value in exposing them to the rest of your application. Whatever the reason, I'm assuming that there are solid design goals in making these guys only package-visible.
Hooking this code into your application can now be done in a controlled manner through your method bridge:
final public class Bridge {
final private Foo1 foo1 = new Foo1();
final private Foo2 foo2 = new Foo2();
final private Foo3 foo3 = new Foo3();
public void bar1() {
foo1.bar1();
}
public void bar2() {
foo2.bar2();
}
public void bar3() {
foo3.bar3();
}
public void bar4() {
foo3.bar4();
}
}
Notice that by using this approach, the fact that bar3() and bar4() are both called on the same classtype (and instance, even) is completely concealed from the user of the bridge. This means the internals of the package structure itself can easily be refactored and reorganized without any external code having to change. The bar4() method could easily be moved to the Foo2 class and nobody would be the wiser. Similarly, access to a method can be removed completely simply be removing it from the Bridge class, allowing classes in the package to continue using the method but denying outside code from seeing it.
