Clone Wars



  • I recently wrote something that added an additional field to a structure. It involved changing the query to retrieve the field, adding the field+getter+setter to the enclosing object, and modifying the query code to grab the extra column from the result set and stuff it into the object.

    The object was Cloneable (Java) and had a simple clone() method implemented as a stub for when additional deep-copy magic was needed. Since I was adding a simple Long, I didn't need to change it.

    Today, someone complains that it's not setting the (new) value I had added. Sure enough, it wasn't, but only for one specific customer. WTF?!

    Long story short, the clone() method was at the top of the file. Buried way down deep at the bottom of the file, more than 2,000 LOC away, was another method:

      public Object myClone() throws CloneNotSupportedException {
        MyObject newObj = new MyObject();
    
        // No fields are copied in the: clone() method, and we need them all
        newObj.x = this.x; // OP: native field
        newObj.y = this.y; // OP: native field
        newObj.z = this.z; // OP: native field
        ...
    
    // Copy new fields added for new special type of customer
    if (customerTypeIsSpecial) {
       newObj.newField1 = this.newField1;
       newObj.newField2 = this.newField2;
       newObj.newField3 = this.newField3;
       ...
    }
    
    return newObj;
    

    }

    I inquire of the developer of this wizardry...

    Well, the clone method didn't have any fields assigned from the old object to the new one, so I added this to copy the fields.

    It's worth noting that for non-special customers, the newFields are all null. In other words, the whole myClone() method can be safely eliminated and replaced with a call to: clone().



  • @snoofle said:

    Buried way down deep at the bottom of the file, more than 2,000 LOC away, was another method

    The force is strong with this one.



  • @flabdablet said:

    The force is strong with this one.

    I think you mean "the farce".



  •  The wheel reinvented. Only square this time.


Log in to reply