Using Builder Pattern to standardize Return data
https://softwareengineering.stackexchange.com/questions/373119
-
06-02-2021 - |
Question
Would it make sense for me to use a builder pattern to return data from an API? Currently I'm just creating the array structure and returning it. In more detail, I have 3 exit places for my class that should be accounted for (one of them being empty results).
Basically it is just a multidimensional array in PHP like below. I'm not sure if I should create a global array, a struct like class, or builder. I would love some input on this for my future work.
$arr['pagination']['total']
$arr['pagination']['page']
$arr['inventory_data']
$arr['errors']
UPDATE: I'm trying it out like so :
public function getMeSomething($input)
{
// -- return 'empty' objects if problems etc. --
if (!$input) {
return (array) (new myBuilderStruct())
->error('the input is missing')
->build();
}
// <method code here>
// -- Return results --
return (array) (new myBuilderStruct())
->total($totalRecords)
->current_page($page)
->limit($limit)
->error((!empty($error)) ? $error : "")
->build();
}
Just to give some more detail I'm using it just to return a data structure from a method, but I want all of my methods that return this data to be the same .
La solution
Pros of your approach
it works
it is readable
Cons:
- it is probably overdesigned.
The last point is something we cannot really tell you - you need to decide for yourself if implementing this fluent interface is really worth the hassle (especially if you currently have just 3 places where you could use it in your application). If you had 30 or 300, I would say yes, it makes sense.
But for 3? I have some doubts. A simple, reusable function with default parameters maybe sufficient for the purpose of creating a uniform return value in all those 3 places, and not necessarily less readable. But maybe the situation is more complex than shown in the question, and I we don't see the whole picture, only you can tell.
Moreover, an array like
$arr['pagination']['total']
$arr['pagination']['page']
$arr['inventory_data']
$arr['errors']
looks like a code smell to me - using a class with members errors
, inventory_data
, and pagination
would probably be more expressive and less error prone.