On Thu, Jul 31, 2025 at 10:42 AM Mihail Liahimov <91lia...@gmail.com> wrote:

> Hi, Rob!
>
> When we want to avoid returning null values, we resort to using exceptions
> so that the client code can somehow handle the absence of values.
> For example:
>
> if ($user->getName() !== null) {
> $this->doSomethingWithUserName($user->getName());
> }
>
> We usually add an exception inside such getters if there is no value:
>
> try {
> $this->doSomethingWithUserName($user->getName());
> } catch (UserNameIsNull);
>

There will be TypeError because "doSomethingWithUserName" should accept
strings.
Using exceptions to check types is rough practice because exceptions aren't
cheap. "if" is cheaper.


>
> This is useful when we need to "do nothing" when there is no value. In my
> opinion, this code looks more declarative.
>
> We can do something like this also with repositories:
>
> try {
> $post = $this->postRepository->get($postId);
>
> // do something with post
> } catch (PostNotFound);
>

Instead of idents inside another block I'd prefer to use early returns:

try {
-- ...
-- ...
-- ...
-- ...
-- ...
} catch (...)

vs

try {
-- ...
} catch (...) {
-- return
}
...
...
...
...

Or even "if"

if (!...) {
-- return ...
}
...
...
...
...



-- 
Best regards,
Dmitrii Derepko.
@xepozz

Reply via email to