Example of JL Component Composition
Java Layers Home


We illustrate an example of JL component composition using the TransportIfc interface:

interface TransportIfc {
 send(Data d);
 recv(Data d);
}

We now define three layers that use this interface.  The TCP layer exports TransportIfc and provides data transport using TCP.  The Secure layer provides data encryption/decryption and the KeepAlive layer automatically exchanges liveness notifications between communicating peers.  The Secure and KeepAlive layers import and export the TransportIfc interface.  These three layers are defined below as classes in JL. 

class TCP implements TransportIfc {..}

class Secure<T implements TransportIfc>
  extends T implements TransportIfc {..}

class KeepAlive<T implements TransportIfc>
  extends T implements TransportIfc {..}

The TCP class is not parameterized, but the Secure and KeepAlive classes are mixins.  In the latter two classes, the type parameter, T, is constrained by TransportIfc--any instantiation of Secure or KeepAlive requires an actual type parameter that implements the TransportIfc interface.  

The type equation below defines a new type, Trans, by composing our three layers.

Trans = KeepAlive<Secure<TCP>>

We say that Trans, which implements a secure TCP transport with the automatic keep-alive feature, is generated by its type equation.  Trans implements TransportIfc because thatís the interface exported by the leftmost, or top, layer in the composition stack.  Compositions are seen as stacks when viewed graphically, as in Figure 1 .

Figure 1 - Trans Layer Composition

Layers in a composition can be thought of as stacked virtual machines that perform feature-specific processing.  Though we haven't shown method implementations, we can walk through a hypothetical invocation of the send() method to illustrate this idea of virtual machines.  When a Trans client invokes send(), the KeepAlive layer at the top of the stack gets control first.  KeepAlive send() simply calls the Secure layer's send().  Next, the Secure layer encrypts the message and then invokes the TCP layer's send() to transmit the encrypted data. The ordering of layers is important in this scheme-if the KeepAlive and Secure layers were reversed, then liveness messages would be sent in the clear rather than encrypted.

The ability to mix and match layers to generate a new type with the precise set of desired features gives JL compositional flexibility.  Every time a new layer is added into a composition, the resulting type is refined with a new characteristic or behavior.  This stepwise refinement of code characterizes JL programming methodology.