Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good/common sense programming practice to make all methods return a MyResult object in PHP?

Working through several layers of an MVC architecture designed program, I find that I would like to have more information on a deeper layer's method return result, and that it's not always that I can anticipate when I'll need this information. And - for abstraction sake - I might not want that method outputting stuff to the application-specific log (that method could be used in a different program), or have a specific application dependent behaviour like other layers above.

For instance, in a given utility function I might have several pre-requisite checks before executing an action, that fail. If I return false on any of them, the caller doesn't know what happened. If I return false and log to the application log what happened, I'm bounding that function to application specific behaviour.

Question is: is it good/common pratice to implement a little class called MyResult and have it return the response status (ok/false), a message, an eventual integer code, and an object placeholder (array or object) where the caller could access the returned object? This MyResult class would be used throughout the whole system and would be a common "dialect" between all methods and their callers. All methods would then return an instance of MyResult, all the times.

like image 983
Pedro Mata-Mouros Avatar asked Jun 12 '11 15:06

Pedro Mata-Mouros


1 Answers

Could you give an example? It seems a bit, but I can be mistaken, that you are having methods you are using statically (even if they are not implemented/called like that they could've been). The basic example of the table-object that can paint itself is called like so: $myTable->paint();. It can return a variable if it worked or not (true/false) but any other thing (like logging) is a function of table() and neither your calling method, nor the return value should have anything to do with that as far as I'm concerned.

Maybe I'm having a hard time understanding what situation you are going to use this for, but if you want to send messages around for some purpose that requires messages (or events etc) you should define those, but I don't see any merit in defining a default returnObject to pass around method-call results.

For errors you have two options: exceptions (that is: things you really don't expect to happen and should halt execution) and errors: expected but unwanted behaviour. The first should be left alone, the second can be tricky, but I'd say the object itself should contain a state which makes it clear what happened.

like image 166
Nanne Avatar answered Sep 25 '22 20:09

Nanne