【发布时间】:2013-01-25 11:00:51
【问题描述】:
我需要使用一些 Java 库,它可能会在一个方法中抛出一些异常并在另一组方法中返回错误代码。到目前为止,它导致了像
这样的丑陋代码val txn = mgr.prepareTransaction()
val accessRecord = txn.readByQuery(...)
var state : Either[MyError, Result] = null //
try {
// do something here
val result = txn.runCodeWithin(new Callable[Result]() {...})
if (result == -1) {
state = Left(CanNotReadRecord)
} else {
state = Right(txn.getCachedRecord())
}
} catch {
case e: Exception => state = Left(GeneralError(e))
} finally {
state match {
case Right(_) => txn.commit();
case _ => txn.rollback();
}
}
我最感兴趣的是摆脱 state 作为 var 和在 finally 块中检查状态的能力。请指教。
【问题讨论】:
-
如果你有相同的模式,你可以将丑陋因素考虑到一个单一的实用方法中,该方法接受 3 个参数(mgr、readByQuery 的 arg 和一个为 runCodeWithin 创建可调用的块)。然后改用实用方法。它不会使这种特殊方法变得漂亮,但至少会减少它的足迹。
-
这就是我实际在做的事情 - 将事务管理和游标提取到具有隐式错误生成器的实用程序方法中。但是它看起来仍然......很奇怪。
标签: scala immutability resource-management