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