1

我有一个大方法,其中一部分检查对象的状态,如果状态无效则抛出异常。我应该提取一个方法吗?新方法“CheckState”将什么都不做或抛出异常。

4

4 回答 4

1
于 2012-06-04T20:33:31.337 回答
1

If I understand you correctly, you mean to say that part of your method checks the state of an object and throws an exception if it is invalid.

You are further asking whether you should move this to its own method(one that checks the state of an object and throws an exception of it is invalid).

The answer really is; probably neither. An exception should really only be thrown in "exceptional" circumstances. If you enter your method and expect the object to be in a valid state, then use it as if it were.

If something occurs that is unexpected, then catch that exception and throw your "InvalidStateException". (If programmed properly this shouldn't even be necessary either.)

If you enter your method and are not sure that your object is in a valid state, then it being in an invalid one is not "unexpected" behavior, and it should be handled differently.

This is where your Check method would come into place. It shouldn't throw an exception but should probably return a boolean, which will determine what you do next. An invalid object in your case is perfectly reasonable, so use your code to handle that case with a check method that returns its valid_state boolean.

This and this describe what I am talking about.

于 2012-06-04T20:34:50.270 回答
1

将状态检查与状态更改代码分开甚至是一种很好的做法。但是,如果您的课程在各处都非常依赖状态,那么您可能应该看看State Design Pattern

在这种模式中,行为差异是通过使用一种方法来建模的,每个 State 类的实现方式都不同。

这可能比以下实现得更好,但它让您尝到了味道:

class FooState {
   FooState handleFoo();
   FooState handleBar();
}

class ValidState {
   FooState handleFoo(){...
   }
   FooState handleBar(){
      return InvalidState(stateful);
   }
}

class InvalidState {
   FooState handleFoo() { throw InvalidState(); }
   FooState handleBar() {

       return ValidState(stateful);
   }
}

class StatefulObject {
   public FooState state;
   public void foo(){ state=state.handleFoo(); }
   public void bar(){ state=state.handleBar(); }
}
于 2012-06-04T20:47:22.220 回答
0

如果它真的什么都不做,那么您应该能够安全地完全删除代码。

否则,代码必须做一些事情。在这种情况下,您应该能够安全地创建一个单独的方法,这肯定会使您的代码更干净。

于 2012-06-04T20:24:51.670 回答