Hot answers tagged null
54
The question is not so much whether you should check for null or let the runtime throw an exception; it is how you should respond to such an unexpected situation.
Your options, then, are:
Throw a generic exception (NullReferenceException) and let it bubble up; if you don't do the null check yourself, this is what happens automatically.
Throw a custom ...
37
IMHO trying to handle null values that you don't expect leads to overly complicated code. If you don't expect null, make it clear by throwing ArgumentNullException. I get really frustrated when people check if the value is null and then try to write some code that doesn't make any sense. The same applies to using SingleOrDefault (or even worse getting ...
36
Is there anything inherently wrong with just storing false as null?
Yes.
If so can you please explain what the down side should be?
NULL is not the same as False.
By definition, comparisons (and logic) that involve NULL should return values of NULL (not False). However, SQL implementations can vary.
True and NULL is NULL (not False).
True ...
34
In your example myApple has the special value null (typically all zero bits), and so is referencing nothing. The object that it originally referred to is now lost on the heap. There is no way to retrieve its location. This is known as a memory leak on systems without garbage collection.
If you originally set 1000 references to null, then you have space for ...
25
Null references aren't "shunned" any more so than exceptions, at least by anyone I've ever known or read. I think you're misunderstanding the conventional wisdom.
What's bad is an attempt to access a null reference (or dereference a null pointer, etc.). This is bad because it always indicates a bug; you would never do something like this on purpose, and ...
23
Consider:
Language,
Framework,
Context.
1. Language
Using ∞ can be a solution for a maximum.
JavaScript, for example, has an infinity. C# doesn't¹.
Ada, for example, has ranges. C# doesn't.
In C#, there is int.MaxValue, but you cannot use it in your case. int.MaxValue is the maximum integer, 2,147,483,647. If in your code, you have a maximum value ...
21
If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.
21
I've been trained to believe that throwing the ArgumentNullException is "correct" but an "Object reference not set to an instance of an object" error means I have a bug. Why?
Suppose I call method M(x) that you wrote. I pass null. I get an ArgumentNullException with the name set to "x". That exception unambiguously means that I have a bug; I should not ...
20
I suppose if you are immediately dereferencing the variable, you could debate either way, but I would still prefer the ArgumentNullException.
It is much more explicit about what is going on. The exception contains the name of the variable that was null, whereas a NullReferenceException does not. Particularly at the API level, an ArgumentNullException makes ...
19
Exceptions should only be thrown when there is an error and asking for a thing is not an error.
Asking for a thing may not be an error, but not having permissions to something you asked for is surely some sort of error. Exceptions are an alternative way of reporting exceptional conditions, to be used instead of special return values (such as null, ...
18
The NullReferenceException basically tells you: you are doing it wrong. Nothing more, nothing less. It's not a full-fledged debugging tool, on the contrary. In this case I'd say you're doing it wrong both because
there is a NullReferenceException
you didn't prevent it in a way you know why/where it happened
and also maybe: a method requiring 20 objects ...
17
What you have there is perfect. It's clear and simple.
If you had several cases testing for null, I'd combine them. This is bad as it tests for (metadata != null) repeatedly.
if ((metadata != null) && (metadata.TypeEnum != CellTypeEnum.Status))
{ ... }
else if ((metadata != null) && (metadata.TypeEnum != CellTypeEnum.Info))
{ ... }
else ...
14
The habit of checking for null to my experience comes from former C or C++ developers, in those languages you have a good chance of hiding a severe error when not checking for NULL. As you know, in Java or C# things are different, using a null ref without checking for null will cause an exception, thus the error will not be secretly hidden as long as you ...
12
By allowing nulls in a boolean field, you are turning an intended binary representation (true/false) into a tri-state representation (true, false, null) where your 'null' entries are indeterminate. The 'null' value is neither appropriately 'true' nor 'false.' What reason would you have to augment your representation to be inaccurate?
Even if you decide on ...
11
The big difference is that if you leave out code to handle NULLs, your code will continue on quite possibly crashing at a later stage with some unrelated error message, where as with exceptions, the exception would be raised at the initial point of failure (opening a file for reading in your example).
11
Use asserts to test and indicate pre/postconditions and invariants for your code.
It makes it so much easier to understand what the code expects and what it can be expected to handle.
An assert, IMO, is a suitable check because it is:
efficient (usually not used in release) ,
brief (usually a single line) and
clear (precondition violated, this is a ...
10
Null isn't any better than a magic number.
The important thing is to NAME the values that have magic effects, if you have to have such values, and to make sure that the definitions of those names are someplace that will be seen by anybody who bumps into the magic value and wtf's.
if (timeout == 4298435) ... // bad.
if (timeout == null) ... // bad.
if ...
10
Use the SQL standard IS NULL or IS NOT NULL to test for NULL
Quote from the Postgresql docs:
Do not write expression = NULL because NULL is not "equal to" NULL.
(The null value represents an unknown value, and it is not known
whether two unknown values are equal.) This behavior conforms to the
SQL standard.
10
The && and || in many languages (C, C++, Java, C#) are short-circuiting, which means that as soon as the answer is known, it stops evaluating. If your language is one of short-circuiting languages, you do not need a nested if, because as soon as metadata != null evaluates to false, the evaluation of the overall expression is going to stop, preventing ...
9
The answer depends on the language you're using.
C/C++
In C and C++, the keyword was NULL, and what NULL really was was 0. It was decided that "0x0000" was never going to be a valid pointer to an object, and so that is the value which gets assigned to indicate that it is not a valid pointer. However, it's completely arbitrary. If you attempted to ...
9
In C and C++, pointers are inherently unsafe, that is, when you dereference a pointer, it is your own responsibility to make sure it points somewhere valid; this is part of what "manual memory management" is about (as opposed to the automatic memory management schemes implemented in languages like Java, PHP, or the .NET runtime, which won't allow you to ...
8
It really should show exactly what you are trying to call. It's like saying "There's a problem. You need to fix it. I know what it is. I'm not going to tell you. You go figure it out" Bit like half the answers on this Stack Overflow, ironically.
So how useful would it be, for example, if you got this...
Object reference (HttpContext.Current) not set to ...
7
It's really only speculation as to why they didn't do it. After all, I don't believe ?? was in the first C# version.
Anyways, I would just use the conditional operator and call it a day:
return (_mywidget != null) ? _mywidget.Length : 5;
The ?? is just a shortcut to the conditional operator.
7
You wouldn't use a Null Object Pattern in places where null (or Null Object) is returned because there was a catastrophic failure. In those places I would continue to return null. In some cases, if there's no recovery, you might as well crash because at least the crash dump will indicate exactly where the problem occurred. In such cases when you add your own ...
7
There is absolutely a way to avoid checking for null here! Use the null object pattern, i.e.
class NullStrategy: Strategy {
public void doSomething() {
}
}
and then the "default" case in createConcreteStrategy is return new NullStrategy() instead of return null, and then you no longer have to check if strategy is null in run.
If you don't want ...
6
Because null values are not a necessary part of a programming language and are a consistent source of bugs. As you say, opening a file may result in failure, which could be communicated back as either a null return value or via an exception. If null values were not allowed then there is a consistent, singular way to communicate failure.
Also, this is not ...
6
Every platform out there is free to define NULL as it pleases.
According to the C Standard, if you assign zero to a pointer it will be converted to a NULL value (for that platform.) However, if you take a NULL pointer and cast it to int, there are no guarantees that you will get zero on every platform out there. The fact however is that on most platforms it ...
6
Another approach is to use the Null Object pattern.
Instead of explicit checks for null, you always return an instance, so in this case you'd have (pseudo-code):
public class NullMetadata
{
VariantInfoMetadata TypeEnum { get; set; }
public NullMetadata()
{
TypeEnum = VariantInfoMetadata.None
}
}
Then instead of
var metadata = ...
5
There are multiple ways to handle this, peppering your code with if (obj != null) {} is not ideal, it is messy, it adds noise when reading the code later during the maintenance cycle and is error prone, as it is easy to forget to do this boiler plate wrapping.
It depends on if you want the code to continue executing quietly or fail. Is the null an error or ...
5
It comes down to what the contract is. If your contract says you can request something that doesn't exist, it should say what happens (null, or null object).
On the other hand, if your contract says you should call a different method first (DoesSomethingExist()) and then call the Get method, then your contract might say that you can only get things that do ...
Only top voted, non community-wiki answers of a minimum length are eligible
