When to wrap a object field's methods or to pass the object itself?

69 Views Asked by At

If a class Foo has a hashmap ie:

public class Foo {

    private HashMap <String, Integer> fooMap;

    //other foo methods

}

When encapsulating the fooMap, what are the circumstances by which the fooMap should have its methods wrapped as seen below:

public class Foo {

    private HashMap<String, Integer> fooMap;

    //other foo methods

    public int getFoo(String s) {

        return fooMap.get(s);

    }

    //other wrapper methods

}

or have the fooMap returned itself:

public class Foo {

    private HashMap<String, Integer> fooMap;

    //other foo methods

    public HashMap<String, Integer>  getFooMap() {

        return fooMap;

    }

}
1

There are 1 best solutions below

0
On

In general it is a bad idea to expose your fields and i would suggest to return copy of your map () instead of the real reference.As your code grows you cannot always follow all the path which the flow can take some other object may take your Foo object map pass it to some other object which will add values and it will take days of debuging to understand what went wrong. Here are some links i found on this topics http://javarevisited.blogspot.co.il/2012/03/private-in-java-why-should-you-always.html and Why encapsulation is an important feature of OOP languages?