Single generic data object vs separate data object for each request/response #129
-
I wonder if it's better to have:
We are developing a large-scale project with complex data structures. Very simplified examples are given below. First approach: class UserData extends Data
{
public function __construct(
public readonly int|Undefined $id,
public string $name,
public AddressData|Undefined $address,
public string|Undefined $phone,
public CarbonImmutable|Undefined $created_at,
public CarbonImmutable|Undefined $updated_at,
) {
}
} Second approach: // global UserData object - e.g. the response after successful insertion into the database
class UserData extends Data
{
public function __construct(
public readonly int $id,
public string $name,
public AddressData $address,
public string|Undefined $phone, // optional
public CarbonImmutable $created_at,
public CarbonImmutable $updated_at,
) {
}
}
// separate DataObject for POST request when creating user
class CreateUserData extends Data
{
public function __construct(
public string $name,
public AddressData $address,
public string|Undefined $phone, // optional
) {
}
}
// separate DataObject for PATCH request when updating only user's address
class UpdateUserAddressData extends Data
{
public function __construct(
public AddressData $address,
) {
}
}
// separate DataObject for PATCH request when updating user
class UpdateUserData extends Data
{
public function __construct(
// ...
) {
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I think it depends on the complexity of the data and you can use both approaches in project. For example, in the project for which we created this package, we almost always use approach one in the beginning. As soon as everything starts getting complicated for a specific case, then we split up these data objects into I think we split up 10 objects in total upon a 200+ data objects project so that's in my opinion the best approach. Keep everything as simple as possible but don't be afraid to split up data objects when it makes your code more readable and more simple. |
Beta Was this translation helpful? Give feedback.
I think it depends on the complexity of the data and you can use both approaches in project. For example, in the project for which we created this package, we almost always use approach one in the beginning. As soon as everything starts getting complicated for a specific case, then we split up these data objects into
Create
,Update
and base data objects.I think we split up 10 objects in total upon a 200+ data objects project so that's in my opinion the best approach. Keep everything as simple as possible but don't be afraid to split up data objects when it makes your code more readable and more simple.