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?
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With