Mutable or immutable class?

后端 未结 8 1893
死守一世寂寞
死守一世寂寞 2020-12-17 21:44

I had read in some design book that immutable class improves scalability and its good practice to write immutable class wherever possible. But I think so immutable class inc

8条回答
  •  清酒与你
    2020-12-17 21:46

    Immutable classes do promote object proliferation, but if you want safety, mutable objects will promote more object proliferation because you have to return copies rather than the original to prevent the user from changing the object you return.

    As for using classes with all static methods, that's not really an option in most cases where immutability could be used. Take this example from an RPG:

    public class Weapon
    {
        final private int attackBonus;
        final private int accuracyBonus;
        final private int range;
    
        public Weapon(int attackBonus, int accuracyBonus, int range)
        {
            this.attackBonus = attackBonus;
            this.accuracyBonus = accuracyBonus;
            this.range = range;
        }
    
        public int getAttackBonus() { return this.attackBonus; }
        public int getAccuracyBonus() { return this.accuracyBonus; }
        public int getRange() { return this.range; }
    }
    

    How exactly would you implement this with a class that contains only static methods?

提交回复
热议问题