December 2002
Intermediate to advanced
288 pages
9h 46m
English
The first rule of thumb when designing a suite of value objects is this: avoid inheritance. There are two basic reasons for this. The first is efficiency. When you send an instance of a class over the wire, you also send information about the class hierarchy. If you run Example 6-1, you’ll see that in Java Development Kit (JDK) 1.4 the cost of one extra level of inheritance is 44 bytes (regardless of whether you use serialization or externalization).
public class FlatHierarchies { public static void main(String[] args) { try { System.out.println("An instance of A takes " + getSize(new A( ))); System.out.println("An instance of B takes " + getSize(new B( ))); System.out.println("An instance of C takes " + getSize(new C( ))); System.out.println("An instance of D takes " + getSize(new D( ))); } catch(Exception e) { e.printStackTrace( ); } } private static int getSize(Object arg) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream( ); ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream); oos.writeObject(arg); oos.close( ); byte[] bytes = byteArrayOutputStream.toByteArray( ); return bytes.length; } protected static class A implements Serializable { } protected static class B extends A { } protected static class C implements Externalizable { public void readExternal(ObjectInput oi) {} public void writeExternal(ObjectOutput oo) {} } protected ...