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

时间:2016-03-10 15:15:15

标签: java serialization coding-style refactoring

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

class Problem {
  private String longString;
  private String firstHalf;
  private String secondHalf;
}
firstHalf secondHalf 是从 longString 计算出来的,并且在我的应用程序中广泛使用,但我不想将它们序列化。现在,为了使该对象的序列化起作用,我需要一个 longString 的setter。我想保护 firstHalf secondHalf longString 计算的不变量,仅当 longString 存在且该值存在时才存在从某种意义上说,传递给 longString 是正确的,可以计算出第一半和第二半。我目前的解决方案是将 longString 的setter写成:

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

此代码还表示 longString 与第一和第二半之间存在紧密关联。

然而,有一件事让我感到困惑的是,方法 setLongString 实际上做了三件事,它的名字并没有反映出它的真实行为。

有没有办法更好地编码?

编辑1: 我正在使用杰克逊的json序列化器,我在第一和第二半都有吸气剂,用@JsonIgnore注释。

我想表达 longString 与它的一半之间的紧密耦合。

2 个答案:

答案 0 :(得分:1)

firstHalf和secondHalf计算可以懒惰地完成(即使用getter)

public void getFirstHalf() {
    if (this.longString != null) {
        this.firstHalf = computeFirstHalf(longString);
    }
    return this.firstHalf;
}
下半场可以遵循同样的原则。

答案 1 :(得分:1)

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.
}