Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best practice for not null if statements

Tags:

php

I've been writing my "If this variable is not empty" statements like so:

if ($var != '') {
// Yup
}

But I've asked if this is correct, it hasn't caused a problem for me. Here is the answer I found online:

if (!($error == NULL)) {
/// Yup
}

This actually looks longer than my approach, but is it better? If so, why?

like image 475
Evan Harrison Avatar asked Jan 31 '12 00:01

Evan Harrison


People also ask

How do you handle null in an if statement?

Use the ISNULL function with the IF statement when you want to test whether the value of a variable is the null value. This is the only way to test for the null value since null cannot be equal to any value, including itself. The syntax is: IF ISNULL ( expression ) ...

IS NOT NULL if statement?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

Which is checking for null a good practice?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.

How do you avoid null?

One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.


1 Answers

Rather than:

if (!($error == NULL))

Simply do:

if ($error)

One would think that the first is more clear, but it's actually more misleading. Here's why:

$error = null;

if (!($error == NULL)) {
    echo 'not null';
}

This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:

$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;

The second conditional if ($error) makes it more clear that type casting is involved.

If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)

like image 120
webbiedave Avatar answered Sep 24 '22 23:09

webbiedave