Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom for container classes [closed]

I have been told to develop my code according to the following code example:

Class Dogs{
   List<Dog> listOfDogs = new ArrayList<Dog>();
   // Setters, getters...
}

Class Dog{
   // Attributes and methods
}

The question is: why is it better to implement a Dogs class as a container for the ArrayList of Dog objects, instead of just referring to a simple ArrayList. Is this considered encapsulation?

like image 695
capovawi Avatar asked Dec 08 '22 08:12

capovawi


2 Answers

Basically, creating a Dogs class provides you with additional layer of indirection.

This means that all your other code will reference (i.e. use) only the Dogs class, but not the internal list. This, in turn, means that whenever you decide to switch from using list to, say, using plain arrays internally (or to change Dogs's implementation in any other way, for that matter), you can readily do so.

That's a motivation for it. As for the question of it being 'better', that depends strongly on whether you can limit usage of the internal container by a stable Dogs's API. If you can, creating a Dogs class is justified. Otherwise, it's simpler and easier to just go ahead and use List.

One example of the aforementioned 'stable API' is an application of the Visitor pattern. In this case, the Dogs class shall have a single visit() method accepting a visitor argument. A visitor 'knows' how to process a Dog, but is completely unaware of the Dogs internal structure. Which is a good thing.

like image 61
shakurov Avatar answered Dec 10 '22 22:12

shakurov


I can see why someone asked you to do this although just like the other answers suggest, this is too broad of a question to answer correctly. Depends on the scenario.

Now the justification here could be that when you have a container for a Dog objects you get to control how these objects are created, accessed and changed. If you just have a List lying around you can't really control proper access or Add/Delete operations to it. However if you have a Dogs class. You can return readonly lists, don't allow addition of dogs that are of certain breed, etc. It can basically be a controller class for all that has to do with dogs.

Class Dogs
{
  List listofDogs = new ArrayList<Dog>();

  public void AddDog(Dog newDog)
  {
     //check if valid
  }

  public List<Dog> getDogs()
  {
    //return readonly dogs collection
  }
}
like image 28
Farhad Alizadeh Noori Avatar answered Dec 10 '22 22:12

Farhad Alizadeh Noori