B
B
BonBon Slick2019-01-21 08:00:56
PHP
BonBon Slick, 2019-01-21 08:00:56

How to avoid checking for NULL without exceptions and if?

I noticed that in huge projects there are too many NULL values, which creates additional logic for checking,
if I forgot to check, a NullPointerException and others fly out. It is possible to throw out an exception, but it is not always possible to skip it, for example, when we use a library, or an apish, and the like.
How to minimize the error due to NULL as much as possible and properly handle such cases?
Exceptions are the same as writing a check, because the exceptions must be handled, otherwise they can break the application on the client. And if by default set 0 for int, '' for string and [] or new Collection(), you need to check for emptiness, length or value.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Kudinov, 2019-01-21
@BonBonSlick

There is no silver bullet for this. It is necessary to consider different cases separately. Unfortunately, you didn't provide any examples.
Somewhere you can get rid of null with a neutral value or behavior: 0for numbers, ''for strings, []or Collection::empty()for a collection/array, NullObject for objects.
Some wrapper over either can help here.
PS Using null with subsequent checks can be quite justified in certain situations and cases.

B
Boris Korobkov, 2019-01-21
@BorisKorobkov

It is necessary to check the data from the user. For example, raise an object by id, check that it exists, check the rights to it. In all normal frameworks, all these checks can be fit in one line. If something is wrong - "not found" or "access denied".
There is no need to check the data in all the insides, because you still need to believe in yourself. If you messed up somewhere - and so there will be an error in the log.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question