I was reading a C# book in which the author (some dude named Jon Skeet) implements a Where function like
public static IEnumerable<T> Where<T> ( this IEnumerable<T> source, Funct<T,bool> predicate )
{
if ( source == null || predicate == null )
{
throw new ArgumentNullException();
}
return WhereImpl(source, predicate);
}
public static IEnumerable<T> WhereImpl<T> ( IEnumerable <T> source, Func<T,bool> predicate )
{
foreach ( T item in source )
{
if ( predicate(item) )
{
yield return item;
}
}
}
Now, I fully understand how this works and that it's equivalent to
public static IEnumerable<T> Where<T> ( this IEnumerable<T> source, Funct<T,bool> predicate )
{
if ( source == null || predicate == null )
{
throw new ArgumentNullException();
}
foreach ( T item in source )
{
if ( predicate(item) )
{
yield return item;
}
}
}
which brings up the question of why would one separate these into 2 functions given that there would be memory/time overhead and of course more code. I always validate parameters and if I start writing like this example then I'll be writing twice as much code. Is there some school of thought which holds that validation and implementation should be separate functions?
Aucun commentaire:
Enregistrer un commentaire