1

I'm creating a model where one element can contain other elements. I'm currently writing the interface to the model, and I'm not sure which is the best of the two options:

Option 1

interface Container {
  List<Element> getElements(); // returns an unmodifiable list.
  void addElement(Element e);
  void removeElement(Element e);
}

Option 2

interface Container {
  List<Element> getElements(); // returns an unmodifiable list.
  void setElements(List<Element> elements);
}

What are the pros/cons of each option? Furthermore, are there "accepted" naming conventions in these cases, like using children instead of elements?

2 Answers 2

1

It's actually a question of "Who manages the list".

In Option 1, you provide the container with the elements, and keep it its responsibility to manage them: The order, maybe reject some elements, etc.

With Option 2, the container is a dumb container. It gets the list from someone else, and has no say as to what's in it or what order it's in.

Option 1 would allow you (If you drop getElements()) to hide the container's content (Or part of the content) from other workflows in your code. It can even allow some sort of multi-threading, by providing thread-safety handling inside the container code (Although this sounds excessive).

As far as naming goes - to me, "elements" kinda means "I don't care what's in there" - so a generic Container would hold Elements. "Children" implies a dependency relation: to handle a Parent, you must handle all its Children (Tree-like fashion).

0

I generally prefer Option 3:

interface Container {
  MutableList<Element> getElements();
}

This is the pattern used by most API's that are written in the .NET framework. It keeps the API as simple as possible -- particularly in .NET where you have property getters as in myContainer.Elements.Add(new Element()).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.