当我们为使用子资源的资源创建打开/关闭机制时,我们有 2 种模式来处理发生错误时的子资源释放:
1
RESULT Open() {
RESULT result;
result = OpenSubResourceA();
if (result == SUCCESS)
result = OpenSubResourceB();
/* Do not handle error case, the convention is that the caller
* will call Close whatever the return code of Open is */
return result;
}
2
RESULT Open() {
RESULT result;
result = OpenSubResourceA();
if (result == SUCCESS)
result = OpenSubResourceB();
if (result != SUCCESS)
ReleaseSubResourceA();
/* Release A if opening B failed since the convention is
* that the caller calls Close only if Open succeeds */
return result;
}
当然,我们可以用超过 2 个子资源进行概括。
你最喜欢的做事方式是什么?为什么?
编辑
感谢您的投入。主要资源不应该处于 Open/Close 调用之外的某个中间状态的想法使我确信 #2 确实是最好的解决方案。