IT评测·应用市场-qidao123.com技术社区

标题: 史上最全EffectiveJava总结(二) [打印本页]

作者: 魏晓东    时间: 2025-3-28 07:43
标题: 史上最全EffectiveJava总结(二)
方法

49、检查参数的有效性

每次编写方法或构造函数时,都应该考虑参数存在哪些限制,并在文档中记载下来,然后在方法的开头显式地检查。
如果没有在方法开头就验证参数,大概会违反故障原子性。因为方法大概会在执行过程中出现让人困惑的非常而失败,或者计算出错误的结果然后返回,甚至大概埋藏隐患,导致将来在不确定的某处代码产生错误。
对于公共方法和受掩护的方法,使用@throws 标签记载违反参数限制会引发的非常,比方 IllegalArgumentException、IndexOutOfBoundsException 或 NullPointerException。见下面例子:
[code]/*** Returns a BigInteger whose value is (this mod m). This method* differs from the remainder method in that it always returns a* non-negative BigInteger.**@param m the modulus, which must be positive* @return this mod m* @throws ArithmeticException if m is less than or equal to 0*/public BigInteger mod(BigInteger m) {    if (m.signum()




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4