gpt4 book ai didi

java - 防御性编程的编辑器模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:52:30 26 4
gpt4 key购买 nike

最近我处理了有关公开内部状态的 FindBugs 警告,即当返回对数组的引用而不是返回数组的副本时。我创建了一些模板来简化代码的转换。

您创建了哪一个来支持防御性编程并想与 SO 人群分享?

到目前为止我创建的模板(作为示例):

创建数组的副本以从方法返回:

final ${type}[] ${result} = new ${type}[ ${array}.length ];
System.arraycopy( ${array} , 0 , ${result} , 0 , ${array}.length );

克隆一个对象:

(${o}!= null?(${type})${o}.clone():null)

最佳答案

我喜欢将“更安全”的 equals() 定义作为模板:

 /**
* Implement equals based on ${cursor}. <br />
* See {@link #compareTo(Object) compareTo}
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(final Object anObject)
{
boolean res = false;
if(anObject == null) { return false; }
if(anObject == this) { return true; }
if(anObject.getClass() == this.getClass())
{
res = this.compareTo(anObject) == 0;
}
return res;
}

要确保始终避免 Eq: equals 方法覆盖父类(super class)中的 equals 并且可能不对称(EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC),其中:

This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use instanceof in the determination of whether two objects are equal.

This is fraught with peril, since it is important that the equals method is symmetrical (in other words, a.equals(b) == b.equals(a)).
If B is a subtype of A, and A's equals method checks that the argument is an instanceof A, and B's equals method checks that the argument is an instanceof B, it is quite likely that the equivalence relation defined by these methods is not symmetric.


这仅适用于实现 Comparable 的类,并允许:

  • 始终相同的 equals 实现;
  • 所有比较逻辑仅位于一个位置(compareTo() 函数);
  • 遵守 Comparable#compareTo() 的 javadoc 要求确保 (x.compareTo(y)==0) == (x.equals(y))(强烈推荐,但并非严格要求)。

关于java - 防御性编程的编辑器模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/374348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com