Imagine you have a class that uses a collection as its internal store.  The class OWNS the collection.  However, you want to be able to provide a copy of that collection to callers so they can serialize the class or dump the contents, whilst wtill maintaining control over it.  How to allow access to the collection without opening a hole for corruption of your map?

For example, the class could return the collection directly.

public Map getMobileRenderingProfiles()
{
   return mobileRenderingProfiles;
}

...but it would allow the caller to do this!

handsetManager.getMobileRenderingProfiles( ).put(“Hello”,”Mum”);

The answer is to return the collection as a read-only copy.  A potentially expensive call, but this kind of thing only tends to be done for debugging purposes, so this is ok (and it is safer to consume CPU than to open your class to corruption).  

public Map getAllMobileRenderingProfiles()
{
   // return a read-only copy of the hashmap
   return UnmodifiableMap.decorate(mobileRenderingProfiles);
}

Access is controlled.

blog comments powered by Disqus