Inner classes

I love Java's inner classes. Most non-ui Java developers seem to ignore them, but I think that's a mistake. Here are a few ways I like to use them:



1. Common implementations of an abstract type.



Using interfaces in an API instead of classes is usually a good idea but it adds a level of indirection. You can compensate by using inner classes to make your API a little easier. Let's say you have a class and a related interface like this:




public interface Value {
int getIntValue();
String getStringValue();
}



public class Foo {
public void doit(Value v) {....}
}


Using the interface instead of an explicit object add a lot of flexibility but unless you provide a default implementation of the interface you've pushed off some tedious work onto your callers. Rather then creating a separate implementation class I like to use inner classes in this case. You could start out with the most common implementation like this...


public interface Value {
int getIntValue();
String getStringValue();

public static class StringVersion implements Value{
private String _s;
public StringVersion(String s) {
_s = s;'
}
public int getIntValue() {
return Integer.parseInt(_s);
}
public int getStringValue() {
return _s;
}
}
}


and then add on later. This works really well when there is more than one implementation as it keeps a level of direct association between the interface and the implementations that isn't there when you use new top level classes.



2. Exception hierarchies



Exception hierarchies are all over the place in the core Java libraries but its rather hard to keep track of the associations without following all the links in Javadoc. I think using this method of child Exceptions being declared as inner classes or the root exception keeps things simpler and easier to maintain.


public class NetworkException extends Exception {

....

public static class Bind extends NetworkException {

public Bind() {
super("Bind Error.....");
}
}

public static class Host extends NetworkException {

public Bind() {
super("Host Error....");
}
}

}




....
throw new Bind.NetworkException();
....


3. Tightly coupled parameter classes/interfaces



Bundling associated parameters into a class or interface is a often a good idea. It allows you to modify the parameters of the method without always needing to find and modify every instance of every call. Rather than create a new top level class or interface for such a construct, use an inner class (or interface) instead.


public class Foo {
public static class Params {
}

public Foo() {
}

public void method(Foo.Params params) {
}
}




Comments

Popular posts from this blog

Shark Crackers

Running roughshod or ripshod

Axis, Axes, Axii?