C#: Encapsulation of for example collections

c#, class, encapsulation

Solution

In example one, it is possible to mutate your collection.

Consider the following:

var passengers = (List<Passenger>)bus.Passengers;

// Now I have control of the list!
passengers.Add(...);
passengers.Remove(...);

To fix this, you might consider something like this:

class Bus
{
  private List<Passenger> passengers;

  // Never expose the original collection
  public IEnumerable<Passenger> Passengers
  {
     get { return passengers.Select(p => p); }  
  }

  // Or expose the original collection as read only
  public ReadOnlyCollection<Passenger> ReadOnlyPassengers
  {
     get { return passengers.AsReadOnly(); }
  }

  public void AddPassenger(Passenger passenger)
  {
     passengers.Add(passenger);
  }
 }

Problem

I am wondering which one of these would be considered the cleanest or best to use and why. One of them exposes the a list of passengers, which let the user add and remove etc. The other hides the list and only let the user enumerate them and add using a special method. Example 1 ``` class Bus { public IEnumerable<Person> Passengers { get { return passengers; } } private List<Passengers> passengers; public Bus() { passengers = new List<Passenger>(); } public void AddPassenger(Passenger passenger) { passengers.Add(passenger); } } var bus = new Bus1(); bus.AddPassenger(new Passenger()); foreach(var passenger in bus.Passengers) Console.WriteLine(passenger); ``` Example 2 ``` class Bus { public List<Person> Passengers { get; private set; } public Bus() { Passengers = new List<Passenger>(); } } var bus = new Bus(); bus.Passengers.Add(new Passenger()); foreach(var passenger in bus.Passengers) Console.WriteLine(passenger); ``` The first class I would say is better encapsulated. And in this exact case, that might be the better approach (since you should probably make sure it's space left on the bus, etc.). But I guess there might be cases where the second class may be useful as well? Like if the class doesn't really care what happens to that list as long as it has one. What do you think?

Original source

Related problems