1

What's the preferred way of checking if the value is null?

Let's say we have some entity, which has properties, which can be null (some of them or all of them).

And I wish to check this in runtime, if some property is actually null or not.

Would you use simple Entity.Property != null check in this case or would you implement a specific method, let's say like

bool HasProperty() {
   return Property != null;
}

What would you choose and why?

Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148

7 Answers7

3

For property values which can be null, my preference is to do the following

  1. Have the property containing the value which can possibly be null
  2. Have another property prefixed with Has and the rest containing the original property name which determines if the other property is non-null
  3. Add an assert into the original property if it's accessed when null

In this example it would be

SomeType Property { 
  get { 
    Contract.Requires(HasProperty);
    return _property; }
}

bool HasProperty {
  get { return _property != null; }
}

The reasoning behind this is that C# does not have a standard way of describing whether or not a value can be null. There are many different conventions and techniques avalaible but simply no standard. And not understanding the null semantics around a value leads to missed null checks and eventually NullReferenceExceptions.

I've found the best way to express this is to make the null feature of a property explicit in the type itself by adding the Has property if and only if the property can be null. It's not a perfect solution but I've found it works well in large projects.

Other solutions I've tried

  1. Do Nothing: This just fails over and over again
  2. Using an explicit Maybe<T> or Option<T> type in the flavor of F#. This works but I find I receive a lot of push-back from developers who've never done functional programming and it leads to a rejection of the idea entirely in favor of #1.
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
1

Just check if the property itself is null, there is no need to create a method for this. Properties are really just methods that are generated by the compiler.

Brian Ball
  • 12,268
  • 3
  • 40
  • 51
1

There is no pattern that covers this. In fact, anything you do to try and make this "easier" could be considered an anti-pattern.

"Hey, don't check if the property is null, use the Is[Property Name]Null property"

Uh, no.

  • If all you do is get a new name for a null check, yes, it's kind of pointless. But if you do like Jared and have the property fail *immediately* if you call the getter when it's null, you are really making things easier. NullReferenceExceptions have a tendency to show up too far from its root cause, but if you fail fast like Jared proposes, they show up much closer, making debugging less painful. – R. Martinho Fernandes Jan 31 '11 at 17:59
  • @Martin that's a code smell. Properties should behave as much like fields as possible. If your property is expected to throw an exception in certain situations, then it should be refactored into a method. –  Feb 01 '11 at 14:45
  • That's good advice. But there are situations when it is justifiable to throw, even from getters. Look at `Stream.Length`: it throws if `Stream.CanSeek` returns false. – R. Martinho Fernandes Feb 01 '11 at 14:58
  • @Martinho that's the exception, not the rule. Also, DateTime.Now is considered to be an outlier in accepted property behaviors. The framework design guidelines say essentially the same thing as I said (I'm not making this stuff up). –  Feb 01 '11 at 19:57
  • +1 Definately an anti-pattern. If null is a valid value for a property, it needs to be able to return that. I don't want to write `Widget widget = obj.IsWidgetNull ? null : obj.Widget` every time I want to get a property value. – Joe Daley Apr 21 '11 at 01:02
0

I would choose to write a separate Has* property only if the property is auto-initializing (i.e. just getting it might cause, say, an empty collection to be allocated) and it makes a performance difference. If getting the property is cheap (as it should be; in some cases you just can't help having it make a difference, though), there's no need for a superfluous Has method.

So no Has for the general case:

public string Foo { get; set; }

But in some cases, it can be a good idea:

private List<string> someStrings = null;

public List<string> SomeStrings {
    get {
        if (someStrings == null)
            someStrings = new List<string>();
        return someStrings;
    }
}

public bool HasSomeStrings {
    get { return (someStrings != null && someStrings.Count > 0); }
}
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • 1
    That's... awful. `derp.SomeStrings.Count > 0` is the only correct solution in this case. Your property will report that there are some strings when, in fact, it actually indicates that the property has been accessed at least once. It says nothing about whether the collection contains any strings whatsoever. –  Feb 01 '11 at 14:47
  • @Will: Well, it seems I forgot the count test from the Has property. You could've just gone and edited it in for all I care, but thanks for pointing it out. – Matti Virkkunen Feb 01 '11 at 17:28
  • eh, I'd rather nitpick. Helps keep my smug quota up. –  Feb 01 '11 at 19:53
0

I check only against null, because every nullable type does internally exactly what you described (but the internal method is called HasValue instead of HasProperty):

http://msdn.microsoft.com/de-de/library/b3h38hb0.aspx

Marc
  • 6,749
  • 9
  • 47
  • 78
0

If Property is something that isn't public, then you would need a method like HasProperty(). Also, if you implement your "nullness" in another way, it would also be good to have a HasProperty() method.

Pedro
  • 382
  • 2
  • 7
0

Null is not necessarily bad. I think it all depends on why you need to check for null to determine how you should check for it.

Kris
  • 1,789
  • 3
  • 18
  • 27