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 theGuardclass.
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
usingstatements in your code:using LightTraveller.Guards; - Simply call
staticmethods of theGuardclass 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.Nullthrows if the generic input is null.Guard.Emptythrows if thestringinput is null, an empty string or consists only of white-space characters.Gurad.NullOrEmptythrows if theIEnumerable<T>input is null, or an empty collection.Guard.Zerothrows if the input is zero.Guard.Negativethrows if the input is negative.Guard.ZeroOrNegativethrows if the input is zero or negative.Guard.Positivethrows if the input is positive.Guard.ZeroOrPositivethrows if the input is zero or positive.Guard.OutOfRangethrows if the genericIComparable<T>input is out of the specified range.Guard.InvalidEnumValuethrows if the input cannot be cast to a member of the specified enumeration.Guard.ZeroPointerthrows if the input isIntPtr.Zero.