Defensive copying and alternatives

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

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

Mungo

The University of Dundee is a registered Scottish Charity, No: SC015096

···

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
www.compbio.dundee.ac.uk

Hi Mungo

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)

I really ought to read my mail before googling to resolve niggling
discussions :wink:

I reached the same conclusion and put a patch together:
http://issues.jalview.org/browse/JAL-2172?focusedCommentId=16044&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-16044

Its not merged in because a few tests fail - but may be a better
solution (and may also prove useful for the AnnotatedCollectionI
containers, too !)

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

I suspect it slipped through because the Collections API was not
released until after the first edition, and there were other priorities
for the second edition. Maybe its time for a review !

.j.

···

On 16/09/2016 14:07, Mungo Carstairs (Staff) wrote: