Domanda

I do not understand how you think about it:https://wiki.php.net/rfc/nullable_types

when It is widely confirmed, that using nulls is bad practice

Where am I wrong?

thanks.

I'm not criticizing !. I do not understand the motivations

È stato utile?

Soluzione

Nulls are “bad” because many languages make every type implicitly nullable – that weakens the type system considerably as every operation may or may not result in a null pointer exception. However, most of the time the expectation is that variables are not null, thus making potential null values even more insidious.

Explicit syntax for nullable types solves part of this problem: because the value may explicitly be null, you can be expected to check first. This strengthens the type system a bit.

More importantly, this makes the type system more self-documenting. With explicitly nullable types there is a clearer difference between “some type T, which could in theory also be null” and “a type that is either T or null – check the value before using”.

On a type theory level, this is just a special case of “union types” (i.e. either–or types). These are frequently used implicitly in dynamic languages like PHP, e.g. strpos() which returns an index or FALSE. That can lead to bugs (e.g. the index zero is also false-y). Being able to explicitly document that with a type system (and allowing potential bugs to be detected via static analysis tools) is great, especially for larger and more mature code bases.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top