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

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:
我正在使用Jackson进行json序列化程序,上半部分和下半部分都有吸气剂,并用@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.
}

08-26 00:16