This throw helper (guard) library allows you to skip typing boilerplate code to guard against unacceptable arguments passed to a method. This helps to produce a cleaner and more readable code
The following method
using LightTraveller.Guards;
public class TicketService
{
private readonly TicketRepository _repository;
private readonly UserService _userService;
private readonly TicketValidator _validator;
public TicketService(TicketRepository repository, UserService userService, TicketValidator validator)
{
if (repository is null)
throw new ArgumentNullException(nameof(repository));
if (userService is null)
throw new ArgumentNullException(nameof(userService));
if (validator is null)
throw new ArgumentNullException(nameof(validator));
_repository = repository;
_userService = userService;
_validator = validator;
}
}
can be rewritten as
using LightTraveller.Guards;
public class TicketService
{
private readonly TicketRepository _repository;
private readonly UserService _userService;
private readonly TicketValidator _validator;
public TicketService(TicketRepository repository, UserService userService, TicketValidator validator)
{
_repository = Guard.Null(repository);
_userService = Guard.Null(userService);
// An overload accepting a custom exception message
_validator = Guard.Null(validator, "Make sure the passed argument is not null.");
}
}
As you can see in the example above, when using Guards library, you do not need to pass the name of the arguments, e.g.,
nameof(repository)
or"repository"
, to the guard methods to be used for throwing exceptions. This is taken care of by using[CallerArgumentExpression]
attribute in the the methods of theGuard
class.
You can add the Nuget package of the LightTraveller.Guards by running the following command in the .NET CLI
dotnet add package LightTraveller.Guards --version <VERSION NUMBER>
For more information please go to the nuget.org page of this library.
- Add this to the
using
statements in your code:using LightTraveller.Guards;
- Simply call
static
methods of theGuard
class by passing the argument to be checked to that method. Each method returns the instance passed to it if it passes the check; otherwise, throws an exception.
For a code sample, please look at the above example.
Guard.Null
throws if the generic input is null.Guard.Empty
throws if thestring
input is null, an empty string or consists only of white-space characters.Gurad.NullOrEmpty
throws if theIEnumerable<T>
input is null, or an empty collection.Guard.Zero
throws if the input is zero.Guard.Negative
throws if the input is negative.Guard.ZeroOrNegative
throws if the input is zero or negative.Guard.Positive
throws if the input is positive.Guard.ZeroOrPositive
throws if the input is zero or positive.Guard.OutOfRange
throws if the genericIComparable<T>
input is out of the specified range.Guard.InvalidEnumValue
throws if the input cannot be cast to a member of the specified enumeration.Guard.ZeroPointer
throws if the input isIntPtr.Zero
.