Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

c# - How can I manage the onslaught of null checks?

Quite often, in programming we get situations where null checks show up in particularly large numbers. I'm talking about things like:

if (doc != null)
{
  if (doc.Element != null)
  {
    ... and so on
  }
  else
    throw new Exception("Element cannot be null");
} else {
  throw new Exception("document cannot be null");
}

Basically, the whole thing turns into an unreadable nightmare, so I'm wondering: is there an easier way to describe what I'm trying to do above? (In addition to null checks, I get things like string.IsNullOrEmpty from time to time.)

Accepted answer: I accepted the answer that has this link because the approach described is innovative, and is precisely what I want. Thanks Shawn!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Check out this article: A fluent approach to C# parameter validation

It's written by one of the Paint.NET Developers. He uses extension methods to simplify and clean up null checking code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...