Objects and methods in the standard libraries doesn’t need to be written nor debugged.
Consider this fragment of code - this is where we ended up after the last post.
The loop in this routine is well written, and obviously correct - but this is mostly because the test is a simple one. It’s easy to see how this might go wrong if the test were more complex.
In 2007 we had the release of C# 3.0 with the included LINQ query language, along with the support in .NET 3.5 for working effectively with sequences of values.
These routines are well designed and robustly implemented - so lets use them to simplify this method.
FirstOrDefault() extension method will return the first item in a sequence that satisfies the
a given predicate. If no match is found, it will return the default value for the result type,
usually a null. (Other related methods to research include
Replacing the loop with the extension method, we get this:
We’ve taken another step forward towards our goal of intention revealing code. There’s no way we can screw up writing a loop if we don’t have to write it ourselves. Better yet, this code is both shorter and easier to read.