If I have an ItemContainer class that contains, for example, items in an order, where each item is an Item object; is it best to have a method like:
ItemContainer->getItems()
that returns an array containing Item objects, or is it better practice to do something like:
ItemContainer->getItem($itemNo)
which returns a single item object for that item number, and forgoes the array. I realise this may be a trivial question or simply one of preference, but I'd like my app to adopt best practices from the start and I'm unsure which way to proceed. I'm writing in PHP, but I figured this pretty much applies to any OOP language.
Best Answer
The principle reasons for not following the
ItemContainer->getItems()
approach and returning an array are:If the caller really wants to have a copy of the array, then
itemContainer->cloneItems()
is much clearer, and less likely to be used inappropriately.If the caller is just wanting to have a single item, then providing a
itemContainer->getItem(index && key)
is clear and efficient
If the caller is wanting to iterate over the items, then providing a
itemContainer->getItemIterator()
is clearer. Depending on the language you may implement
itemContainer->VisitItems(visitor)
where visitor is a visitor class, delegate or function pointer.
Hopefully, I've given you some ideas on how this can be approached differently