Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OO Design Encapsulation

I have a question with regard to encapsulation. As I know, encapsulation enables to hide the implementation details using private/protected data members and provides public methods and properties to operate on the data. The idea here is to prevent the direct modification of the data members by the class consumers.

But I have a concern with the property getters or other public methods which return private/protected data members. For ex: if I have class like this

public class Inventory
{
    private List<Guitar> guitars = new List<Guitar>();

    public void AddGuitar(string serialnumber, string price)
    {
        Guitar guitar = new Guitar(serialnumber, price);
        guitars.Add(guitar);
    }

    public List<Guitar> GetGuitars()
    {
        return guitars;
    } 
}

Now if the Inventory class consumer calls GetGuitars, he is going to get the list of guitars being maintained in the Inventory class. Now the consumer can modify the list, like delete/add/modify the items. For me it looks like we are not encapsulating. I think that I should be returning a copy of the Guitar list items in the GetGuitars(). What do you think?.

Is my understanding of the encapsulation right?.

Thanks

like image 811
user1719287 Avatar asked Oct 07 '22 10:10

user1719287


1 Answers

Encapsulating lists of objects can be achieved quite nicely by restricting access to them using a suitable interface.

I think you're right to control additions to your list via your AddGuitar method as you can exert control over what goes in. You can reinforce this design, IMHO, by altering GetGuitars to return IEnumerable instead of List.

This reduces the control the caller has on your list, whilst also being non-committal in returning an abstract type. This way your internal data structure can change without the public interface needing to also.

like image 103
David Osborne Avatar answered Oct 10 '22 03:10

David Osborne