Lifted from discussion in http://issues.jalview.org/browse/JAL-2001.


There are pro's and con's to returning a copy of internal state rather the 
actual object (e.g. ColumnSelection.getSelected()).

Pro: prevents inadvertent modification that might break the internal 
consistency of the object

Con: performance cost of making the copy


Jim is right in pointing out that Java semantics don't really help with this 
(e.g. you have to document behaviour manually).


I fell to wondering why Java doesn't provide things like a 'read-only' view of 
a collection...thinks...you could wrap a List with a List that overrides all 
update methods to throw an exception...Googled for this...well well it is 
already there...

Collections.unmodifiableList(List)


It seems to provide the best of both worlds (with suitable documentation of the 
API of course).

I'm just very surprised it doesn't get a mention in Effective Java Item 39, 
which discusses defensive copying, and that it's not more widely known (at 
least I've never come across it being used).


It sounds useful to me.

Care is still needed with the semantics e.g. you can still modify the internals 
of the objects in the list (unless they are themselves immutable e.g. 
List<Integer>).

But that also arises with a 'defensive copy' of a list if it a shallow copy, as 
for example new ArrayList(List) provides.


Mungo


Mungo Carstairs
Jalview Computational Scientist
The Barton Group
Division of Computational Biology
School of Life Sciences
University of Dundee, Dundee, Scotland, UK.
www.jalview.org<http://www.jalview.org/>
www.compbio.dundee.ac.uk<http://www.compbio.dundee.ac.uk/>

The University of Dundee is a registered Scottish Charity, No: SC015096
_______________________________________________
Jalview-dev mailing list
Jalview-dev@jalview.org
http://www.compbio.dundee.ac.uk/mailman/listinfo/jalview-dev

Reply via email to