[Biojava-l] Immutable objects and ChangeListeners

Thomas Down td2@sanger.ac.uk
Mon, 8 Jan 2001 19:42:31 +0000


On Mon, Jan 08, 2001 at 06:22:23PM +0000, Keith James wrote:
> 
> I have a question re. objects designed to be immutable under all
> circumstances and yet implementing Changeable.
> 
> e.g. I wanted FastaSearchResult to be immutable but also to implement
> Annotatable (the search header contains a lot of fairly loosely
> formatted, but worthwhile data). This means that it has to implement
> add/removeChangeListener.
> 
> I suppose I could implement the methods as stubs which do nothing.
> I've seen this elsewhere in Biojava, I think. As the methods return
> nothing and can't throw exceptions I guess this should work. However
> is it good that someone who uses these methods (and is therefore
> expecting the object to change) should be able to add/remove a
> Listener? Or think that they had, when in fact nothing had happened.

I don't see a problem here at all.  If you call addChangeListener
on any Changable, you're asking to be notified if that object
ever changes.  If it happens to be an immutable implementation,
then it's fine to make addChangeListener a stub method -- for
the specific case of an immutable object a stub method will
fully comply with the contract.

> As the methods are not allowed to throw exceptions, how can you
> politely say "Are you sure you want to listen for changes - this
> object is immutable" ?

No, please don't get into this.  We've got lots of interfaces
where both mutable an immutable implementations are potentially
useful.  Code can add ChangeListeners if they're worried about
the object changing during some kind of computation (often, you
just want the simplest case of locking an object be adding
an ALWAYS_VETO listener).  As soon as you start complaining
when someone tries an addChangeListener on an immutable object,
then client code has to know what the mutability status of
a given object is, and you're diluting the power of the
interfaces for no particularly good reason (IMHO).

Or am I missing something?

   Thomas.
-- 
``If I was going to carry a large axe on my back to a diplomatic
function I think I'd want it glittery too.''
           -- Terry Pratchett