声纳说mutable members should not be stored or returned directly
Mutable objects are those whose state can be changed. For instance, an array is mutable, but a String is not. Mutable class members should never be returned to a caller or accepted and stored directly. Doing so leaves you vulnerable to unexpected changes in your class state.
Instead, a copy of the mutable object should be made, and that copy should be stored or returned.
This rule checks that arrays, collections and Dates are not stored or returned directly.
我正在尝试存储一个日期。为了解决声纳警报,我创建了两个辅助方法来返回原始日期的副本。
示例A:
public static Date clone(Date originalDate) {
if(date != null) {
return new Date(originalDate.getTime());
}
return null;
}
示例 B:
public static Date clone(Date originalDate) {
if (date != null) {
return (Date)originalDate.clone();
}
return null;
}
如果我使用构造函数方式(示例 A),我会丢失包含原始日期的可能的额外信息。
我应该使用构造函数(示例 A)还是使用克隆(示例 B)复制原始日期?
最佳答案
Should I copy my originalDate with the constructor (example A) or with clone (example B)?
选择更具可读性的方式。即示例 A。
但是Ternary Operator在这里有用。
您可能想看看这里:Clone() vs Copy constructor- which is recommended in java
关于java - 克隆日期的辅助方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37729117/