java - 使用取决于其他字段的字段序列化对象

标签 java serialization coding-style refactoring

假设我有一个具有给定结构的类:

class Problem {
  private String longString;
  private String firstHalf;
  private String secondHalf;
}

firstHalfsecondHalf 是根据 longString 计算的,并在我的应用程序中广泛使用,但我不想序列化它们。现在,为了使该对象能够序列化,我需要一个 longString 的 setter 。我想保护 firstHalfsecondHalflongString 计算得出的不变量,仅当 longString 存在并且该值存在时才存在传递给 longString 在某种意义上是正确的,可以计算前半部分和后半部分。我当前的解决方案是将 longString 的 setter 写成这样:

public void setLongString(String value) {
  this.longString=value;
  this.firstHalf=computeFirstHalf(value);
  this.secondHalf=computeSecondHalf(value);
}

此代码还暗示了 longString 与前半部分和后半部分之间的紧密相关性。

然而,让我烦恼的一件事是,该方法 setLongString 实际上做了三件事,而且它的名称并没有反射(reflect)它的真实行为。

有没有更好的方法来编码?

编辑1: 我正在使用 Jackson 到 json 序列化器,并且我有前半部分和后半部分的 setter/getter ,并用 @JsonIgnore 进行注释。

我想表达 longString 与其半部分之间的紧密耦合。

最佳答案

class Problem {
  private String longString;
  private String firstHalf;
  private String secondHalf;

  //Getters of All Variables
    ......
    ......
    ......

  // Setters of All Variables.

  public void setLongString(String longString){
     this.longString = longString;
     }

  // public but no Arguments so that user won't be able to set this Explicitly but 
  //make a call Outside of the Class to set Only and only if longString is there.

  public void setFirstHalf(){   
       if(this.longString == null)
            throw new Exception("Long String is Not Set.");
       this.firstHalf = this.computeFirstHalf(this.longString);
   }

     // public but no Arguments so that user won't be able to Set Explicitly but 
    //make a call Outside of the Class to set Only and only if longString is there.

   public void setSecondHalf(){  
       if(this.longString == null)
            throw new Exception("Long String is Not Set.");
       this.secondHalf = this.computeSecondHalf(this.longString);
   }
//private method not Accessible outside of Class
   private String computeFirstHalf(final String value){ 
     //Your Logical Code. 
    }
 //private method not Accessible outside of Class
   private String computeSecondHalf(final String value){ 
        //Your Logical Code.
}

关于java - 使用取决于其他字段的字段序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920385/

相关文章:

java - 自动增量字段不返回值(非主键) - Spring boot JPA

java - 如何获取上一个URL页面?引荐来源网址不起作用

python - 我如何处理 django 嵌套模型?

java - 将 boolean 值序列化为 "1"和 "0"而不是 "true"和 "false"

c++ - 将 std::shared_ptr<> 序列化进出二进制流

coding-style - 阻止 PhpStorm 对齐关联数组

c++ - 这种风格好吗?

java - 使用 Junits 测试线程

java - 使用 KeyEvent(KeyPressed、KeyTyped 等)将字符附加到 JTextArea

coding-style - Smalltalk 公共(public)方法与私有(private)/ protected 方法