Skip to content

Instantly share code, notes, and snippets.

@kgiszewski
Created August 2, 2018 16:12
Show Gist options
  • Save kgiszewski/6535f033e754ed968b99c59e418e846e to your computer and use it in GitHub Desktop.
Save kgiszewski/6535f033e754ed968b99c59e418e846e to your computer and use it in GitHub Desktop.
Mandate
public static class Mandate
{
public static void That<TException>(bool condition, string message) where TException : Exception
{
if (!condition)
{
var exceptionInstance = (TException)Activator.CreateInstance(typeof(TException), message);
throw exceptionInstance;
}
}
}
@kgiszewski
Copy link
Author

kgiszewski commented Aug 2, 2018

Syntactic sugar for statements like this:

Instead of:

if(x < 10)
{

}

It would be:

Mandate.That<InvalidOperationException>(x >= 10, $"{x} must be less than 10");

Instead of:

if(x == null)
{

}

It would be:

Mandate.That<NullReferenceException>(x != null, $"{x} was null!");

@kgiszewski
Copy link
Author

Most useful for business rule enforcement and validation.

For example, we can't send an invoice if the invoice is null, therefore Mandate that it is not null before sending out.

@zpqrtbnk
Copy link

zpqrtbnk commented Aug 2, 2018

Cons: it will build and allocate the exception message string on each test, even when not throwing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment