Friday, October 9, 2009

Academic Excercise 1 for Java

So I was asking myself, "Self, would it be possible in Java, like in some of the coolboy languages, in one statement, to wrap an arbitrary hunk of code with resource allocation and cleanup?" It turns out there's a not-too-crazy way as long as your arguments can be marked final:

/**
* Provides resource-safe services for client code.
*/
public class DbKit {
protected DbKit()
{
}
interface DbTask<E>
{
abstract E run(Db db) throws Exception;
}

/**
* Along with DbTask, provides a means to wrap instantiation, opening,
* try { do } finally{close} around any task.
*/
private static <E> E run(DbTask<E> t) throws Exception
{
Db db= new Db();
db.open();
try
{
return t.run(db);
}
finally
{
db.close();
}
}
public static SomeRec insertSomeRec(final long lv,final String sv) throws Exception
{
return run(new DbTask<SomeRec>(){
public SomeRec run(Db db) throws Exception
{
SomeRec r = new SomeRec ();
r.setLongVal(lv);
r.setStrVal(sv);
db.insert(r);
return r;
}});
}
public static void updateRec(final long kv,final String newStatus) throws Exception
{
run(new DbTask<Object>(){
public Object run(Db db) throws Exception
{
SomeRec.update(db,kv,newStatus);
return null;
}});
}
}

No comments:

Post a Comment