If I've got an array or generic list or even a dictionary and I want to first do some checks to see if the object is valid, do I:
- Check for null
- Just check for someCollection.count > 0
- both
Do I check for null then check for count or is checking for count good enou开发者_开发问答gh and I don't need to check for null first?
My problem with OOP and C# often is to know when to check for nulls vs just count on collections. And if it's null then what to return if it's null and lest say you're tryign to return an itemin that collection through a property as an example.
You can't check for Count on a null collection.
An empty collection and a null collection are two different things. So you should check for both, otherwise always initialize your collections so you'll never run into null problems. Or for a simple solution, just return a new collection, then let your calling code handle the count check.
List<Type> someCollection = new List<Type();
if(someCollection == null)
return new List<Type>();
Count will not work on null objects.
Here is some boiler plate code you can use:
Debug.Assert(collection != null);
Debug.Assert(collection.Count > 0);
if (collection == null) {
throw new ArgumentNullException("collection");
}
if (collection.Count == 0) {
throw new ArgumentException("collection should have at least one member");
}
Asserting is really important and should be practiced by more .Net devs.
Crashing early can be key to writing robust code. If there are any parameters that a method you are writing should NEVER get passed, it may be better to crash at that point as opposed to writing corrupt data to the DB.
You also need a robust logging mechanism in place so you can log all those nasty things that are going on.
When you have control over the creation of these collections, you can make your API easier to use by never returning null. If there are no elements, just return an empty collection. If performance is a concern, you can create a single static instance and always return that, or use an EmptyEnumerator.
精彩评论