Friday, July 2, 2010

How to make a copy of a whole object holding multiple parts in an exception safe manner?




Java training


Java's unique architecture enables programmers to develop a single application that can run across multiple platforms seamlessly and reliably. In developing java application in web, Java training you gains extensive experience with Java and its object-oriented features. You get Java training to create robust console and GUI applications and store and retrieve data from relational databases.

This article ensured that if construction of the whole object failed, the resources of all fully constructed parts were released. Careful use of try/finally blocks and statement ordering - essentially, like this:

public class Part implements Cloneable

{

...

public void dispose();

}

public class Whole

{

...

public void copy(Whole other)

{

Part t1 = (Part)other.p1.clone();

if (t1 != null) {

try {

Part t2 = (Part)other.p2.clone();

if (t2 != null) {

t1.setParent(this);

t2.setParent(this);

// pivot point

Part swap1 = t1;

t1 = p1;

p1 = swap1;

Part swap2 = t2;

t2 = p2;

p2 = swap2;

}

}

finally {

t2.dispose();

}

}

finally {

t1.dispose();

}

}

private Part p1, p2; // never null

}

The exception safety guarantees make sense in Java and should be applied when writing or reviewing code. The problem is that the Java language offers almost no in-built support for this activity. In design, as in life, you learn more from making the journey than you do from reaching the destination.

No comments:

Post a Comment