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.
1
The principle reasons for not following the ItemContainer->getItems()
approach and returning an array are:
- The initial implementation is likely to just return a reference to the original array, which would then allow the caller to modify the underlying collection. This is considered bad practice.
- The next work around is then to make a copy of the array and return that instead. This is bad because a caller may think they are still modifying the underlying collection, and it is also expensive for large collections.
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
4
Why not both? Generally, since before 5.4 PHP did not support dereferencing the return of a function, it was commonplace to return an array of objects, and then if the key to the returned array was passed into that function, the function would return only that value.
It’s PHP, so you are working in a dynamically typed language. If you want more surety, you could always create a separate object for storing the items, like ItemCollection
. This would be an approach you would see in languages like Java
or C#
.
it depends:
-
returning an array allows you to pass it directly into the idiomatic foreach of the language
-
but using index-based get means you don’t need to allocate the array and push all items into it.
3