Sunday, August 26, 2012

Most Java objects are not immutable

For many junior programmers fact that Java objects are not immutable is like a science. Recently, our junior programmer has asked me to debug the next code as he was so confused about the output:

private SomeObject{

private AnotherObject anObj;

public setAnotherObject (AnotherObject anObj){
  this.anObj = anObj;
}

useObject(){
System.out.println("Object value is " + this.anObj.getX()); // line 15
}

}


private ActionObjet{

private someMethod(){
     private AnotherObject anObj = new AnotherObject();
     anObj.setX(55);
     SomeObject sm = SomeObjec();
     sm.setAnotherObjec(anObj);
//here goes stupidity
     anObj.setX(999);
//here goes another stupidity
     sm.useObject();
// he gets that output is 999
// oh my God he says, its something unrealistic and so on...IT SHOULD BE 55. I AN CERTAIN
}

}

Main problem is if you give an object to another object instance variable and change that object somewhere in the future the object instance variable refers to the change object.

In order not to make so stupid mistakes give your junior programmers a book about Java language!

No comments:

Post a Comment