代码之家  ›  专栏  ›  技术社区  ›  Łukasz Chorąży

使用依赖于其他字段的字段序列化对象

  •  1
  • Łukasz Chorąży  · 技术社区  · 9 年前

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

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

    上半场 下半场 根据以下公式计算 长字符串 和在我的应用程序中广泛使用,但是我不想序列化它们。现在,为了使这个对象的序列化工作,我需要一个setter 长字符串 .我想保护不变量 上半场 下半场 根据以下公式计算 长字符串 ,仅存在于 长字符串 存在,并且该值传递给 长字符串 在可以计算第一和第二半的意义上是正确的。我目前的解决方案是让setter 长字符串 这样写:

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

    此代码还意味着 长字符串 以及第一和第二半部分。

    然而,有一件事让我恼火,那就是这个方法 设置长字符串 实际上有三件事,它的名字并不能反映它的真实行为。

    有没有更好的编码方法?

    编辑1: 我正在使用Jackson to json序列化程序,我有前半部分和后半部分的getter,用@JsonIgnore注释。

    我想表达两者之间的紧密耦合 长字符串 它是两半。

    2 回复  |  直到 9 年前
        1
  •  1
  •   Vikrant Kashyap    9 年前
    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.
    }
    
        2
  •  1
  •   shark    9 年前

    firstHalf和secondHalf计算可以轻松完成(即使用getter)

    public void getFirstHalf() {
        if (this.longString != null) {
            this.firstHalf = computeFirstHalf(longString);
        }
        return this.firstHalf;
    }
    

    下半场也一样。