我想重写一个有太多嵌套if
语句的方法.
我提出了这种方法,并希望你的意见:
public void MyMethod() { bool hasFailed = false; try { GetNewOrders(out hasFailed); if(!hasFailed) CheckInventory(out hasFailed); if(!hasFailed) PreOrder(out hasFailed); // etc } catch(Exception ex) { } finally { if(hasFailed) { // do something } } }
Graeme Perro.. 9
我做过类似的事情,但没有异常处理:
BOOL ok = CallSomeFunction(); if( ok ) ok = CallSomeOtherFunction(); if( ok ) ok = CallYetAnotherFunction(); if( ok ) ok = WowThatsALotOfFunctions(); if( !ok ) { // handle failure }
或者如果你想要聪明:
BOOL ok = CallSomeFunction(); ok &= CallSomeOtherFunction(); ok &= CallYetAnotherFunction(); ...
如果您正在使用异常,为什么需要hasFailed
变量?
我做过类似的事情,但没有异常处理:
BOOL ok = CallSomeFunction(); if( ok ) ok = CallSomeOtherFunction(); if( ok ) ok = CallYetAnotherFunction(); if( ok ) ok = WowThatsALotOfFunctions(); if( !ok ) { // handle failure }
或者如果你想要聪明:
BOOL ok = CallSomeFunction(); ok &= CallSomeOtherFunction(); ok &= CallYetAnotherFunction(); ...
如果您正在使用异常,为什么需要hasFailed
变量?
并不是的.如果您的"catch"块捕获到错误,您的方法应引发异常.
据我所知,这是一个级联步骤的例子,如果第一个和第一个和第二个有效,将执行第二个和第三个步骤,即返回hasFailed == false.
使用Template Method和Decorator设计模式可以使代码更加优雅.
您需要一个接口,具体实现,抽象类和抽象类的几个子类.
public interface Validator { public boolean isValid(); } public class GetNewOrders implements Validator { public boolean isValid() { // same code as your GetNewOrders method } } public abstract class AbstractValidator implements Validator { private final Validator validator; public AbstractValidator(Validator validator) { this.validator = validator; } protected boolean predicate(); protected boolean isInvalid(); public final boolean isValid() { if (!this.validator.isValid() && predicate() && isInvalid()) return false; return true; } } public class CheckInventory extends AbstractValidator { public CheckInventory(Validator validator) { super(validator); } @Override public boolean predicate() { return true; } @Override public boolean isInvalid() { // same code as your CheckInventory method } } public class PreOrder extends AbstractValidator { public CheckInventory(Validator validator) { super(validator); } @Override public boolean predicate() { return true; } @Override public boolean isInvalid() { // same code as your PreOrder method } }
现在你的方法可以看起来更优雅:
public void MyMethod() { bool success = false; try { Validator validator = new GetNewOrders(); validator = new CheckInventory(validator); validator = new PreOrder(validator); success = validator.isValid(); } finally { if (!success) { // do something } } }
Validator对象可以在一行中创建,但我更喜欢这种样式,因为它明确了验证的顺序.在链中创建新的验证链接是子类化AbstractValidator类以及谓词和isInvalid方法的实现的问题.