Pregunta

I once read that having nullable types is an absolute evil. I believe it was in an article written by the very person who created them(in Ada?) I believe this is the article

Anyway, so what if by default a language like C# used non-nullable types? How would you replace some of the common idioms in C# or Ruby or any other common language where null is an acceptable value?

¿Fue útil?

Solución

Instead of outright declaring that nullable types are evil, I would posit: most languages graft nullability onto entire kinds of types, when the two concepts should really be orthogonal.

For example, all non-primitive Java types (and all C# reference types) are nullable. Why? We can go back & forth, but ultimately I'll bet the answer comes down to "it was easy". There's nothing intrinsic to the Java language that demands widespread nullability. C++ references offered a fine example of how to exorcise nulls at the compiler level. Of course, C++ has a lot more ugly syntax that Java was explicitly trying to curtail, so some good features ended up on the cutting floor alongside the bad.

Nullable value types in C# 2.0 offered a step in the right direction -- decoupling nullability from unrelated type semantics, or worse, CLR implementation details -- but it's still missing a way to do the opposite with reference types. (Code contracts are great & all, but they're not embedded in the type system the way we're discussing here.)

Plenty of functional or otherwise obscure languages got these concepts "straight" from the beginning...but if they were in widespread use, we wouldn't be having this discussion...

To answer your question: banning nulls from a modern language, wholesale, would be just as foolish as the so-called "billion dollar mistake." There are valid programming constructs where nulls are nice to have: optional parameters, any sort of default/fallback calculation where the coalesce operator leads to concise code, interaction with relational databases, etc. Forcing yourself to use sentinel values, NaN, etc would be a "cure" far worse than the disease.

That said, I'll tentatively agree with the sentiment expressed in the quote, so long as I may elaborate to fit my own experience:

  1. the # of situations where nulls are desirable is smaller than most people think
  2. once you introduce nulls into a library or codepath, it's much harder to get rid of them than it was to add them. (so don't let junior programmers do it on a whim!)
  3. nullable bugs scale with variable lifetime
  4. correlary to #3: crash early

Otros consejos

We'd use option types for the (very) few places where allowing a null value is actually desirable, and we'd have a lot less obscure bugs since any object reference would be guaranteed to point to a valid instance of the appropriate type.

Haskell is a powerful language that doesn't have the concept of nullity. Basically, every variable must be initialized to a non-null value. If you want to represent an "optional" variable (the variable may have a value but it may not), you can use a special "Maybe" type.

It's easier to implement this system in Haskell than C# because data is immutable in Haskell so it doesn't really make sense to have a null reference that you later populate. However, in C#, the last link in a linked list may have a null pointer to the next link, which is populated when the list expands. I don't know what a procedural language without null types would look like.

Also, note that many people above seem to be suggesting replacing nulls with type-specific logical "nothing" values (999-999-9999, "NULL", etc.). These values don't really solve anything because the problem people have with nulls is that they are a special case but people forget to code for the special case. With the type-specific logical nothing values, people STILL forget to code for the special case, yet they avoid errors that catch this mistake, which is a bad thing.

I think you are referring to this talk: "Null References: The billion dollar mistake"

You can adopt a simple rule: All variables are initialized (as a default, this can be overridden) to a immutable value, defined by the variable's class. For scalars, this would usually be some form of zero. For references, each class would define what its "null" value is, and references would be initialized with a pointer to this value.

This would be effectively a language-wide implementation of the NullObject pattern: http://en.wikipedia.org/wiki/Null_Object_pattern So it doesn't really get rid of null objects, it just keeps them from being special cases that must be handled as such.

Tcl is one language that not only does not have the concept of null but where the concept of null itself is at odds with the core of the language. In tcl we say: 'everything is a string'. What it really means is tcl has a strict value semantics (which just happens to default to strings).

So what do tcl programmers use to represent "no-data"? Mostly it's the empty string. In some cases where the empty string can represent data then its typically one of:

  1. Use empty string anyway - the majority of the time it makes no difference to the end user.

  2. Use a value you know won't exist in the data stream - for example the string "_NULL_" or the number 9999999 or my favourite the NUL byte "\0".

  3. Use a data structure wrapped around the value - the simplest is a list (what other languages call arrays). A list of one element means the value exist, zero element means null.

  4. Test for the existence of the variable - [info exists variable_name].

It is interesting to note that Tcl is not the only language with strict value semantics. C also has strict value semantics but the default semantics of values just happen to be integers rather than strings.

Oh, almost forgot another one:

Some libraries use a variation of number 2 that allows the user to specify what the placeholder for "no data" is. Basically it's allowing you to specify a default value (and if you don't the default value usually defaults to an empty string).

Null is not the problem, it is the language allowing you to write code that accesses values that can possibly be null.

If the language would simply require any pointer access to be checked or converted to a non-nullable type first, 99% of null related bugs would go away. E.g. in C++

void fun(foo *f)
{
    f->x;                  // error: possibly null
    if (f)              
    {
        f->x;              // ok
        foo &r = *f;       // ok, convert to non-nullable type
        if (...) f = bar;  // possibly null again
        f->x;              // error
        r.x;               // ok
    }
}

Sadly, this can't be retrofitted to most languages, as it would break a lot of code, but would be quite reasonable for a new language.

We'd create all kinds of strange constructs to convey the message of an object 'being invalid' or 'not being there', as seen in the other answers. A message that null can convey very well.

  • The Null Object pattern has its disadvantages, as I explained here.
  • Domain-specific nulls. This forces you to check for magic numbers, which is bad.
  • Collection wrappers, where an empty collection means 'no value'. Nullable wrappers would be better, but that doesn't differ much from checking for null or using the Null Object pattern.

Personally, I would write some C# preprocessor that allows me to use null. This would then map to some dynamic object, which throws a NullReferenceException whenever a method is invoked on it.

Back in 1965, null references may have looked like a mistake. But nowadays, with all kinds of code analysis tools that warn us about null references, we don't have to worry that much. From a programming perspective null is a very valuable keyword.

Realistically speaking, in any powerful programming language that allows pointers or object references in the first place, there are going to be situations where code will be able to access pointers which have not had any initialization code run upon them. It may be possible to guarantee that such pointers will be initialized to some static value, but that doesn't seem terribly useful. If a machine has a general means of trapping accesses to uninitialized variables (be they pointers or something else), that's better than special-casing null pointers, but otherwise the biggest null-related mistakes I see occur in implementations that allow arithmetic with null pointers. Adding 5 to a (char*)0 shouldn't yield a character pointer to address 5; it should trigger an error (if it's appropriate to create pointers to absolute addresses, there should be some other means of doing it).

What would we do without NULL? Invent it! :-) You don't have to be a rocket scientist to use 0 if you are looking for an inband pointer value to express actually not a pointer.

We use either

  1. Discriminators. An extra attribute or flag or indicator that says that a value is "null" and must be ignored.

  2. Domain-Specific Nulls. A specific value -- within the allowed domain -- that is interpreted as "ignore this value". For example, a social security number of 999-99-9999 could be a domain-specific null value that says the SSN is either unknown or not applicable.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top