In a previous post I looked at the GaurdClauses library that can simplify the usual guard checks we sometimes need to write. In the comments someone mentioned the Pitcher library that accomplishes the same thing so I thought I’d check it out here.
First, the NuGet package needs to be installed and a using Pitcher; directive added, then we can make use of the library.
As an example, without the library you might end up with some code like the following:
public static void AddNewPerson(string name, int ageInYears)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException($"Cannot be null, empty, or contain only whitespace.", nameof(name));
}
if (ageInYears < 1)
{
throw new ArgumentOutOfRangeException(nameof(ageInYears), "Must be greater than zero.");
}
// Add to database etc.
}
This is just some boilerplate type code to check for null/empty strings and that the age that’s passed in is positive.
With the Pitcher library this could be refactored to the following (I’ve left the GaurdClauses code commented as a comparison):
public static void AddNewPerson(string name, int ageInYears)
{
// GuardClauses version:
// Guard.Against.NullOrWhiteSpace(name, nameof(name));
// Guard.Against.NegativeOrZero(ageInYears, nameof(ageInYears));
// Pitcher version:
Throw.ArgumentNull.WhenNullOrWhiteSpace(name, nameof(name));
Throw.ArgumentOutOfRange.WhenLessThan(ageInYears, mustBeMoreThan:0, nameof(ageInYears));
// or more simply:
Throw.ArgumentOutOfRange.WhenNegativeNumber(ageInYears, nameof(ageInYears));
}
Pitcher allows you to throw either an ArgumentOutOfRangeException or an ArgumentNullException when using this syntax and also provides ways to throw other exception types when a given condition is true, for example:
Throw.When(ageInYears == 42, new InvalidOperationException("This age has no meaning"));
You can find the source code and more examples on GitHub and don’t forget to say hi/thanks to the project maintainer Alex Kamsteeg and tell him you heard about Pitcher here :)
SHARE: