[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: the benefits of immutability

Vadim Nasardinov wrote:

>    class Subclass extends Superclass {
>        private int m_num;
>        public Subclass(String str, int num) {
>            super(str);
>            m_num = num;
>        }
>        public boolean equals(Object obj) {
>            // try and replace this with an implementation that takes
>            //  m_num into account
>            return super.equals(obj);
>        }
>    }

What's the problem with this?

public boolean equals(Object obj) {
   if (!(obj instanceof Subclass)) return false;

   Subclass that = (Subclass)obj;

   return super.equals(that) && (this.m_num == that.m_num);

I think the main design problem in Java is that immutability is just a 
convention, but inappropriate language constructs are used to enforce 
that convention. Either you completely forget about enforcing 
immutability and rely on intelligent programmers to do it right, or 
invent a language construct that explicitly says what you want. In Java, 
one could have added a class modifier "immutable" and, for example, 
require that all fields in an immutable class are final.

(I suspect there are some nasty corner cases, but it should be doable...)


Pascal Costanza               University of Bonn
mailto:costanza@web.de        Institute of Computer Science III
http://www.pascalcostanza.de  Ro"merstr. 164, D-53117 Bonn (Germany)