Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
    
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 5: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 5:22
1  
@Demian: null is certainly a valid value for objects. The trouble is that, we want to completely avoid System.NullReferenceExceptions 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 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
Thanks! That gives an interesting addition we hadn't thought about. –  Peter K. Jun 2 '11 at 19:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.