Prefer Using Objects when returning large amount of data

When returning large data, it can be obvious to use Arrays. But Arrays make poor object-to-object data transfer mechanisms in object-oriented programming. Objects are main focus of  Object-oriented programming and it should be. This means that each array should be converted into an object, and collections too.

When one object makes a request to another object, it should generally get back an object unless the response is scalar. For example, asking for a data set from the database ought to generate an object, not an associative array of data.

Using objects allows us for type evaluation and type hinting, and creates additional type safety for your application. Objects can be made immutable, and can have methods that access bits of data; arrays can be changed, and have no methods. Naked arrays form excellent value objects that can be hinted on, ensuring the fidelity of the data in the future.

When returning a collection of value objects, you’ll want to make sure the data is homogeneous – that is, the value objects are all of the same type. Otherwise, returning an array is perfectly valid. Collections should only contain objects of a single type.

Of course, returning an object or a collection can have some unintended side effects. For starters, you can’t return a malformed value object, so you’ll need to throw more exceptions when the object can’t be created due to some error. That will mean additional error handling for specific error conditions in the calling object.

You should also consider returning an array if the call is solely internal (between protected methods, for example); value objects should be used for external calls, but arrays are perfectly suitable for internal calls.

Finally, when it comes to defining your return values, use exceptions to denote errors, and only return when you have a fully formed object or collection to return. This will help improve your application’s error handling, and make explicit the conditions by which failure occurs. In addition, by having a single, consistent return value, you can know that when you get a response, the request you made was successful.

Comments


Prefer Using Objects when returning large amount of data When returning large data, it can be obvious to use...

Read Post

Prefer Using Objects when returning large amount of data When returning large data, it can be obvious to use...

Read Post

Leave a Reply

Your email address will not be published. Required fields are marked *