PHP – Best Practices for Returning an Array of Objects

object-orientedPHP

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:

  1. 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.
  2. 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

Related Topic