Java – Passing a private member collection to another class

javaobject-oriented-design

Suppose I have a Map which is a private member variable of my class A.

In the same class I create an instance of class B, call it objB, by passing the map to B's constructor.

Obviously this is wrong, because I have leaked a private field to an object of a different class. That class might later on decide to modify the map passed to it, which would ruin everything.

Is it preferable to 1) pass is using Collections.unmodifiableMap or maybe 2) copying it? If there's another, better approach, I'd be glad to see it.

In case the map is modified in class A, objB should know the new map immediately. And this means I'd have to update the map in objB every time I modify it (but not if I pass it ad unmodifiable list).

I think option 2 is better, because in 1) we pass an unmodifiable collection to B, and B assumes the collections passed to it are modifiable.

class A {
    Map<String, Integer> map;

    public A() {
        map = new HashMap<String, Integer>();
        B objB = new B(map); //option 1
        B objB = new B(Collections.unmodifiableMap(map)); //2
        B objB = new B(new HashMap(map)); //3
    }
}

class B{
    Map<String, Integer> map;

    public B(Map<String, Integer> map) {
        this.map = map;
    }

    //use data from the map to do stuff
}

Best Answer

In case the map is modified in class A, objB should know the new map immediately.

If by know immediately you mean assume the same state immediately without doing anything about it then B should just hold a reference to the map. You can protect it with unmodifiableMap. This approach is not multi threaded friendly since A is still free to mutate the map when B might be traversing it.

If by know immediately you mean deal with the change in state in some way then use the observer pattern. B is an observer of the state of A. When A changes state it should notify all observers. This way A is not forced to expose its reference to the map to keep B up to date.

It would probably be a good idea to read up on immutability and defensive coping.

Related Topic