`
leonzhx
  • 浏览: 791675 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Item 38: Check parameters for validity

阅读更多

1.  A general principle is that you should attempt to detect errors as soon as possible after they occur. Failing to do so makes it less likely that an error will be detected and makes it harder to determine the source of an error once it has been detected.

 

2.  For public methods, use the Javadoc @throws tag to document the exception that will be thrown if a restriction on parameter values is violated.

 

3.  For an unexported method, you as the package author control the circumstances under which the method is called, so you can and should ensure that only valid parameter values are ever passed in. Therefore, nonpublic methods should generally check their parameters using assertions.

 

4.  Assertions throw AssertionError if they fail. And unlike normal validity checks, they have no effect and essentially no cost unless you enable them, which you do by passing the -ea (or -enableassertions) flag to the java interpreter.

 

5.  It is particularly important to check the validity of parameters that are not used by a method but are stored away for later use. Constructors represent a special case, It is critical to check the validity of constructor parameters to prevent the construction of an object that violates its class invariants.

 

6.  The fewer restrictions that you place on parameters, the better, assuming the method can do something reasonable with all of the parameter values that it accepts.

 

7.  Each time you write a method or constructor, you should think about what restrictions exist on its parameters. You should document these restrictions and enforce them with explicit checks at the beginning of the method body.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics