tags:

views:

49

answers:

2

I've a situation described below

Model class (M) which contains a hashmap (h) as a private field ( getter & setter exposed ).
A new class (A) with access to (M) needs to modify (M)'s hashmap (h)

which of the following could be a better way of achieving this

a. use (h)'s getter. i.e (M).getMap().put(a,b) everytime I want to populate this map

b. create a local map populate it and then use (M).setMap(local hash)

c. add a method in (M) addMapEntry(key, value) { (h).put(key, value); } and call (M).addMapEntry in (A)

a. seems somewhat insecure as we are exposing private reference object. b. would consume more memory and hence I always prefer using c.

Could anyone tell if there's any better alternative to achieve this ??

Thanks.

+2  A: 

c.

The hashmap represents part of M's state, so M should control whats in it. Methods call on M are then free to add entries to the map, delete them, or even erase the map completely, dependent on the semantics of the operation, all without clients even being aware that there is a hashmap underneath it all. Thats the essence of encapsulation.

Visage
+1 Totally agree
Jason W
A: 

(C), without doubt.

A has, at the very least, ties your implementation of the "internal" store to always be HashMap based. Who cares? Maybe tomorrow it will be a DB table, or a property file, or a List...

B is too horrible to contemplate. Same problem of A, compounded with the fact that assuming that the "container" class can be called by more than one client, you risk overwriting concurrent changes, even if they were aimed at keys that you don't intend to touch.

p.marino