public class Square {
     private intsideLength;
    private intarea; // Not a good idea 
    publicSquare(int length) {
       sideLength = length;
    } 
    public intgetArea() {
        area =sideLength * sideLength;
        returnarea;
    } 
    /* it is abad idea because if you add mutator and accessor to your fields
     then youneed always to recalculate area during setSideLength method invocation
     */
    public intgetSideLength() {
        returnsideLength;
    } 
    public voidsetSideLength(int sideLength) {
       this.sideLength = sideLength;
        area =sideLength * sideLength; //here is problem root, you need to update state of
object instantly!
    } 
}  
Howit must be:  public class Square { 
    private intsideLength; 
    publicSquare(int length) {
       sideLength = length;
    } 
    public intgetArea() {
        returnsideLength * sideLength;
    } 
    public intgetSideLength() {
        return sideLength;
    } 
    public voidsetSideLength(int sideLength) {
       this.sideLength = sideLength;
    } 
}
                            
Comments