Skip to content

thomasgalliker/Guards

Repository files navigation

Guards

Version Downloads

Guards

This Guards project is a light-weight toolbox which helps you to protect your public interfaces against invalid parameters being passed over. It is one of the fundamentals in object oriented programming that you clearly shield your internals from invalid external signals.

Download and Install Guards

This library is available on NuGet: https://www.nuget.org/packages/Guards/ Use the following command to install Guards using NuGet package manager console:

PM> Install-Package Guards 

You can use this library in any .Net project which is compatible to PCL (e.g. Xamarin Android, iOS, Windows Phone, Windows Store, Universal Apps, etc.)

Available Guards

Category Guards Type of exception
Boolean Guard.ArgumentIsTrue
Guard.ArgumentIsFalse
ArgumentException
Enumerable Guard.ArgumentNotNullOrEmpty ArgumentException
Null Guard.ArgumentNull
Guard.ArgumentNotNull
ArgumentException
ArgumentNullException
Numeric Guard.ArgumentIsBetween
Guard.ArgumentIsGreaterOrEqual
Guard.ArgumentIsGreaterThan
Guard.ArgumentIsLowerOrEqual
Guard.ArgumentIsLowerThan
Guard.ArgumentIsNotNegative
ArgumentOutOfRangeException
Reflective Guard.ArgumentMustBeInterface
Guard.ArgumentMustNotBeInterface
ArgumentException
String Guard.ArgumentHasLength
Guard.ArgumentHasMaxLength
Guard.ArgumentHasMinLength
Guard.ArgumentNotNullOrEmpty
ArgumentException
ArgumentException
ArgumentException
ArgumentNullException or ArgumentException

API Usage

The usage of Guards is very easy.

  • Add namespace import using Guards;
  • Type Guard. and select the preferred guard method.

Most of the Guard methods provide two overloads: One which takes the guarded parameter as an expression and one that takes the guarded parameter as well as the name (as a string) of the parameter. Take whatever fits you better. Keep in mind that expressions have a minor performance drawback but give you better maintainability. It's all about trade-offs.

public void AddPerson(string name, Address address)
{
    // Example usage of guards with expressions
    Guard.ArgumentNotNullOrEmpty(() => name);
    Guard.ArgumentNotNull(() => address);
    
    // Example usage of guards withouot expressions
    Guard.ArgumentNotNullOrEmpty(name, nameof(name));
    Guard.ArgumentNotNull(address, nameof(address));
    
    // Further code omitted...
}

Contribution

New guards are added when desired. Since this is an open source project, everyone is highly welcome to contribute and add new guards. However, the proposals should follow the existing pattern. A minimum of governance is required. Thank you for understanding.

License

Guards is Copyright © 2019 Thomas Galliker. Free for non-commercial use. For commercial use please contact the author.

About

Protects your public APIs

Resources

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

Packages