http://www.javaworld.com/javaworld/javatips/jw-javatip30.html
This article first looks at single polymorphism and, by iteratively extending and improving an example in Java, goes on to explore multiple polymorphism in greater detail.
In my previous Java Tip, I discussed how you can get your compiler to check that constant values are valid. As I mentioned in that tip, although the use of these constructs makes code more readable, it can lead to a series of if/else if
clauses in the client code. This new Java Tip also incorporates typesafe
constants and a technique that can be used to remove the aforementioned condition checking.
Single polymorphism is achieved by method overriding. Listing 1 provides an example of single polymorphism, demonstrating how classes that implement the Traceable
interface simply write their current state to System.out
. Instances of Traceable
can be registered with the TraceManager, which will invoke the Trace()
method on each of these instances in TraceAll()
.
public interface Traceable { public void Trace(); } public class Foo implements Traceable { public void toString() {/* return state of object*/}; public void Trace() { System.out.println( this ); } } public class TraceManager { public void Register( Traceable item ) { } public void TraceAll() { /* iterate all Traceable objects and invoke Trace()*/ } }
The code in Listing 1 works fine if you only want to trace your objects to System.out
. However, if you then wanted to trace these objects to a logfile or via a socket, you're in trouble! A bad solution would be to define a set of interfaces, one for each type, as show in Listing 2.
public interface SystemTraceable { public void Trace();} public interface LogFileTraceable { public void Trace();} public interface SocketTracable { public void Trace();}
What's the problem with this approach? You have to implement a new interface each time your requirements change, resulting in a proliferation of interfaces and classes which can make a design difficult to understand and extend.
Multiple polymorphism is when an abstract class uses another abstract class. Listing 3 shows how multiple polymorphism solves the problem introduced in Listing 2. An OutputDevice
abstraction has been introduced for traceable objects to write to. With this design, any traceable object can write to any OutputDevice
.
public interface OutputDevice { public void Write( String out ); } public class SystemOutput implements OutputDevice { public void Write( String out ) { System.out.println( out ); } } public class LogFileOutput implements OutputDevice {/* impl */ } public interface Traceable { public void Trace( OutputDevice device); } public class Foo implements Traceable { public void toString() {/* return state of object*/}; public void Trace( OutputDevice device) { device.Write( toString ); } } public class TraceManager { public void Register( Traceable item ) { } public void TraceAll( OutputDevice device) { /* iterate all Traceable objects and invoke Trace( device )*/ } }
Using multiple polymorphism leads to a more scalable and extensible design. As new OutputDevice
classes are identified and implemented, the TraceManager
class remains unaltered -- as do the classes that implement Traceable
.
As illustrated and stated above, you can get designs that are more scalable and extensible with multiple polymorphism. But there is still one hurdle to overcome.
Say, for example, you now want to extend your design to allow different levels of tracing that can be altered at run time -- that is, you want to be able to specify to the TraceManager
that objects should trace in "verbose" mode at one point during execution and in "minimal" mode at another. If runtime behavior changes are not required, you could consider subclassing Foo in Listing 1 to implement a "verbose" Trace()
, "minimal" Trace()
, and so on, and then register the appropriate subclass instances with TraceManager
. As with the example in Listing 2, a proliferation of subclasses can lead to a design that is difficult to understand and extend. Listing 4 illustrates one approach to solving this problem.
public class Mode { private Mode() {} public static final MINIMAL = new Mode(); public static final VERBOSE = new Mode(); // } //OutputDevice as in Listing 3. public interface Traceable { public void Trace( OutputDevice device, Mode mode); } public class Foo implements Traceable { private void MinimalTrace(OutputDevice device){/* write state to device*/} private void VerboseTrace(OutputDevice device){/* write state to device*/} public void Trace( OutputDevice device, Mode mode) { if(Mode.MINIMAL==mode)
MinimalTrace( device ); else if(Mode.VERBOSE==mode) VerboseTrace( device ); } } public class TraceManager { public void Register( Traceable item ) { } public void TraceAll( OutputDevice device, Mode mode) { /* iterate all Traceable objects and invoke Trace( device, mode ) */ } }
A typesafe
constant class has been added to the program to specify the current mode. TraceManager
delegates the mode parameter along with the OutputDevice
to the traceable objects. Foo now has to check the mode parameter to determine the appropriate level of tracing to perform.
This design works well, and it leads me neatly back to a question I addressed in my previous tip on type safe constants -- how can you eliminate the if/else if
clause associated with enumerated parameters?
Those readers who have progressed from C to C++ and now to Java may be familiar with a technique that was used in C (before C++ became mainstream) to eliminate giant switch statements by mapping an enum
to a pointer-to-function in a table. If you are not familiar with pointer syntax in C, don't worry: Listing 5 simply demonstrates a mapping from an enumerated type to a function.
void Func1() {} void Func2() {} //etc enum{TYPE1,TYPE2,MAX}; void GiantSwitch( int type ) { switch( type ) { case TYPE1 : Func1();break; case TYPE2 : Func2();break; //etc } } //would become typedef void (*PFUNC)(); PFUNC funcTable[ MAX ]; void Init() { funcTable[ TYPE1 ] = Func1(); funcTable[ TYPE2 ] = Func2(); //..etc } void NoSwitch( int type ) { //range check funcTable[ type ] (); }
Those of you who have come to Java directly from C++ may be interested in experimenting with C structs with embeddedfuncTables
to emulate C++ virtual functions.
Anyway, back to the plot!
As Java doesn't have functions or pointers to functions, we can't port the C code to Java. However, Listing 5 demonstrates a mapping from an enumerated type to a function, and Listing 6 shows you how to achieve the same effect in Java.
Listing 6: Improving the design
//everthing else the same as Listing 4. public class Foo implements Traceable { private Hashtable map = new Hashtable(); private class MinimalTrace implements Traceable {/* impl */} private class VerboseTrace implements Traceable {/* impl */} public Foo() { //initialize map map.put( Mode.MIMINAL, new MinimalTrace() ); map.put( Mode.VERBOSE, new VerboseTrace() ); } public void Trace( OutputDevice device, Mode mode) { Traceable t=(Traceable)map.get( mode ); t.Trace( device ); } }
Foo now has innerclasses that implement the different levels ofTrace()
and uses a Hashtable to map the Mode
to the implementation class. To improve the efficiency of the Trace()
method, we can introduce a currentMode
instance variable with an associatedcurrentImpl
to avoid the overhead of the Hashtable.get()
method, as shown in Listing 7.
public class Foo implements Traceable { private Mode currentMode; private Traceable currentImpl; private Hashtable map = new Hashtable(); private class MinimalTrace implements Traceable {/* impl */} private class VerboseTrace implements Traceable {/* impl */} public Foo() { //init map as Listing 6 //assign currentMode and currentImpl to a default } public void Trace( OutputDevice device, Mode mode ) { if(mode!=currentMode) { currentMode=mode; currentImpl=(Traceable)map.get( mode ); } currentImpl.Trace( device ); } }
One final area of improvement would be to defer the instantiation of the implementation classes until the classes are required, a technique known as lazy instantiation. I will discuss lazy instantiation in depth in a future article, including how the implications and benefits for Java differ from those for C++.
I will leave it as an exercise for the reader to modify the design of Foo
to incorporate lazy instantiation.