Should I always encapsulate an internal data structure entirely?

Posted by Prog on Programmers See other posts from Programmers or by Prog
Published on 2014-05-27T01:23:51Z Indexed on 2014/05/27 3:40 UTC
Read the original article Hit count: 209

Please consider this class:

class ClassA{

    private Thing[] things; // stores data

    // stuff omitted

    public Thing[] getThings(){
        return things;
    }

}

This class exposes the array it uses to store data, to any client code interested.

I did this in an app I'm working on. I had a ChordProgression class that stores a sequence of Chords (and does some other things). It had a Chord[] getChords() method that returned the array of chords. When the data structure had to change (from an array to an ArrayList), all client code broke.

This made me think - maybe the following approach is better:

class ClassA{

    private Thing[] things; // stores data

    // stuff omitted

    public Thing[] getThing(int index){
        return things[index];
    }

    public int getDataSize(){
        return things.length;
    }

    public void setThing(int index, Thing thing){
        things[index] = thing;
    }

}

Instead of exposing the data structure itself, all of the operations offered by the data structure are now offered directly by the class enclosing it, using public methods that delegate to the data structure.

When the data structure changes, only these methods have to change - but after they do, all client code still works.

Note that collections more complex than arrays might require the enclosing class to implement even more than three methods just to access the internal data structure.


Is this approach common? What do you think of this? What downsides does it have other? Is it reasonable to have the enclosing class implement at least three public methods just to delegate to the inner data structure?

© Programmers or respective owner

Related posts about design

Related posts about object-oriented