Reputation: 11
Is it ok to write return blank object? when the return type is class.
public static function createBook($book_data): BookModel
{
try {
$book = new BookModel;
$book->fill($book_data);
$book->save();
return $book;
}
catch(\Exception $e) {
log::error($e->getMessage());
$book = new BookModel;
return $book;
}
}
Upvotes: 1
Views: 66
Reputation: 3467
You're in for pain if you return empty objects:
Although in some situations empty state objects are okay, if you have to ask then you most likely will handle it incorrectly anyway.
Since you have to check against this empty object anyway, returning null is still an okay solution. If you're on php7.1 then the return type can stay (note the questionmark).
public static function createBook($book_data): ?BookModel
{
try {
$book = new BookModel;
$book->fill($book_data);
$book->save();
return $book;
}
catch(\Exception $e) {
log::error($e->getMessage());
return null;
}
}
IMO, a better aproach would be to allow the error to propagate up and let you catch it somewhere else. Looks like you're using laravel, so the error will be logged anyway. So, for example, if you're in a database transaction, the transaction can fail safely:
public static function createBook($book_data): BookModel
{
$book = new BookModel;
$book->fill($book_data);
$book->save();
return $book;
}
Upvotes: 1
Reputation:
I say it depends on what you want to do if (in this case) the exception is thrown.
false
. Returning an empty BookModel
is basically saying that everything went fine and it's much easier to check if something is false
than checking if an attribute of an object is empty.If it doesn't really mind that the book is empty (i.e. your code doesn't assume books are always filled), I think it is okay to return an empty book. However i'd change the code a bit:
public static function createBook($book_data): BookModel
{
$book = new BookModel();
try {
$book->fill($book_data);
$book->save();
}
catch(\Exception $e) {
log::error($e->getMessage());
}
return $book;
}
Upvotes: 0