Lifted from discussion in

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 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...


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. 

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


Mungo Carstairs
Jalview Computational Scientist
The Barton Group
Division of Computational Biology
School of Life Sciences
University of Dundee, Dundee, Scotland, UK.<><>

The University of Dundee is a registered Scottish Charity, No: SC015096
Jalview-dev mailing list

Reply via email to