8

We are implementing some web services, and need to ensure that some of our methods always return non-null values.

We've investigated two ways of doing this:

Both approaches work, but I'm wondering whether there are any other approaches that we should consider.

How would you enforce non-null return values?


Looks like there was a similar question on SO, and Jon Skeet recommends the Code Contract approach.

Peter K.
  • 3,828
  • 1
  • 23
  • 34
  • 1
    It's been years sice I've used C# seriously at all, but why would you need to enforce returning non-null values? Generally, `null` is a perfectly valid return value. – Demian Brecht May 30 '11 at 05:18
  • 1
    Are you looking for a way to ensure that null is never possibly returned, or a way to enforce that null return values are treated as runtime errors? – Kevin Hsu May 30 '11 at 05:22
  • 1
    @Demian: `null` is certainly a valid value for objects. The trouble is that, we want to completely avoid `System.NullReferenceException`s in the receivers of the `null`. – Peter K. May 30 '11 at 12:20
  • @Kevin: The former: `null` is never possibly returned. – Peter K. May 30 '11 at 12:21
  • 1
    Providing you have the tooling available I would definitely go with code contracts. You can then use static analysis to find/eliminate possible null references - pretty much any other approach will only help you at runtime (and obviously contracts will give you that too). – FinnNk May 30 '11 at 22:30

1 Answers1

2

If you can be 100% certain that there will always be a valid value to return, then the code contracts method makes perfect sense, and you can go on your way.

Now, if there is a possibility of a situation where the method might not have a valid value to return, then you can still use the code contract method and implement the null object pattern. The issue with the pattern is that you still have to, kind of, check for null but the client will never get a NullReferenceException.

Steven Evers
  • 28,200
  • 10
  • 75
  • 159