Re: [OxLUG] Web platforms

Top Page
Attachments:
Message as email
+ (text/plain)
Delete this message
Reply to this message
Author: Chris Wareham
Date:  
To: Oxfordshire Linux User Group Discussion List
Subject: Re: [OxLUG] Web platforms
Hubert Matthews said on 25/01/2010 21:57:
> Chris Wareham wrote:
>> The value versus reference aspect is covered well in the "Effective
>> Java" book, which should be made required reading material for every
>> Java programmer.
>
> Indeed it is. How many Java programmers do you know that have read this
> book? Not enough in my experience.
>


Very true. The second edition was a worthwhile update as well, seeing
as some of the items covered in the first one were less relevant once
Java acquired generics and enumerations.

>> With the collection classes, best practice it to return an immutable
>> version from bean getters. For instance:
>>
>> import java.util.*;
>>
>> public class Foo {
>>       private List<String>  items = new ArrayList<String>();

>>
>>       public void addItem(final String i) {
>>           items.add(i);
>>       }

>>
>>       public List<String>  getItems() {
>>           return Collections.unmodifiableList(items);
>>       }
>> }

>
> I see you've also read "Java Concurrency in Practice", another essential
> read for any programmer these days, regardless of which language they use.
> There is lots of good stuff in JCP regarding concurrency, immutability
> and other important stuff for multicore programs.
>


I haven't read that particular book, but I just looked at Amazon and
ended up ordering it - so thanks for the mention! The immutability
thing is something that I picked up from reading about the design of
the Java class library. A lot of people moan about things like the
immutability of the String class, but understanding why it was a
conscious decision to make it both immutable and final was an important
insight for me.

>> The downside to this is that an attempt to call a modifying List method
>> on the object reference returned by getItems() results in a run time
>> exception rather than a compilation error. In practice it works well -
>> you just need to make sure the items in the list are immutable as well
>> if you want to go the whole hog (the Strings in my example are
>> immutable already of course). It would have been good to have had the
>> List interface be immutable, and an MutableList interface extending it.
>> Still, this is better than returning a copy every time, which is what
>> appears to be best practice in C++.
>
> const std::list<std::string> & would be my choice rather than a copy in
> C++, depending on whether you want a real copy that won't change
> underneath you or you are prepared to accept that the list might change.
> And, of course, C++ does check attempted mutations of the returned list by
> the client at compile time.
>


Chris