java - 克隆日期的辅助方法?

标签 java

声纳说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/

相关文章:

java - 获取URL地址

java - 如何处理 JOptionPane.showConfirmDialog 中的选项类型

java - SWIG - 为具有四个传递字节数组的参数的函数创建类型映射

java - 有 subview 时,Android onInterceptTouchEvent 不会执行操作

java - 改变锁对象

java - 使用Java访问Magento API : Procedure ххх not present

java - 将 BigInteger 转换为键

java - C#AES256加密Java解密时如何处理BadPaddingException

java - 如何使用 Apache Commons DirectoryWalker?

java - 如何使用 UI 在 android 中修剪视频?