|
|
|
|
|
by gouranga
5114 days ago
|
|
You miss one important point, which I've learned from many years of using .Net: Which dereference in your LINQ expression is causing the NullReferenceException? Try solving that problem when it goes pop in production and you have a couple of million quid in flight! I'd write it as follows (probably wrapped as a generic function of T: public Thing GetItemWithName(ICollection<Thing> collection)
{
Thing output;
int found;
// preconditions
Check.IsNotNull(collection, "collection was null");
foreach(var item in collection)
{
// ref checks
Check.IsNotNull(item, "item was null");
Check.IsNotNull(item.Property, "item.Property was null");
Check.IsNotNullOrWhiteSpace(item.Property.Name, "item.Property.Name was null or whitespace");
if (string.Compare(item.Property.Name, "Blah!", StringComparison.InvariantCultureIgnoreCase) != 0)
continue;
found++;
// rule check
Check.IsTrue(found <= 1, "Found more than expected single element in collection");
output = item;
}
// postconditions
Check.IsNotNull(output, "output null. Expected reference");
return thing;
}
Note: I tend to write proper industrial grade stuff that has to work every time without fail or any edge cases or conditions. These conditions are prescribed up front. Zero bugs and fail early is the only acceptable outcome which is why this is verbose. |
|