danielwertheim

danielwertheim


notes from a passionate developer

Developer that lives by the mantra "code is meant to be shared".

Share


Tags


Disclaimer

This is a personal blog. The opinions expressed here represent my own and not those of my employer, nor current or previous. All content is published "as is", without warranty of any kind and I don't take any responsibility and can't be liable for any claims, damages or other liabilities that might be caused by the content.

Ensure.That v2 - yet another simple guard clause project

Daniel WertheimDaniel Wertheim

Recently I releasedEnsure.That v2.0.0, which is a simple guard clause project that simplifies and unifies your validation of arguments, for .Net4+, Silverlight, Windows Phone, WinRT.

It’s easy to get started. It’s distributed using NuGet and exists either as a dll or as a source package.

install-package ensure.that  

or for the source distribution:

install-package ensure.that.source  

What does it bring?

Simplified and unified argument validation.

public void Something(string myString) {  
    Ensure.That(myString).IsNotNullOrEmpty();
    ...
}

If you want the name of the argument as the value for ArgumentException.ParamName, you pass it:

public void Something(string myString) {  
    Ensure.That(myString, "myString").IsNotNullOrEmpty();
    //OR
    Ensure.That(myString, nameof(mystring)).IsNotNullOrEmpty();
    ...
}

You can chain:

public void Something(string myString) {  
    Ensure.That(myInt).IsGte(1).And().IsLte(10);

    //same as
    Ensure.That(myInt).IsGt(1).IsLt(10);

    //But could be simplified
    Ensure.That(myInt).IsInRange(1, 10);

    //You can assign the value to e.g. a property
    MyProperty = Ensure.That(myInt).Is(2).Value;
    ...
}

Wait, a magic string for the parameter name?

Yes, indeed. First. There’s an alternative so that you don’t need a magic string. Second. If you are, like me, a happer Visual Studio user cause of the daily use of ReSharper, I can tell you, it picks up those strings when you do e.g. name refactorings.

To get rid of the need of passing a string and instead use lambdas, you need to add an extenstion method as described here: https://github.com/danielwertheim/ensure.that/wiki/support-for-lambda-expressions

After that you can do:

public void Something(string myString) {  
    Ensure.That(() => myString).IsNotNullOrEmpty();
    ...
}

The reason to why this is not included, is that: the lambda expression-tree has negative effects on performance, as it needs to compile the expression to extract the value. May not sound like a big deal, but I want you to be aware of it, hence why you need to include it manually.

Help!

There are probably a bunch of stuff you can add that is missing. Please do. Follow this guide, and I’ll accept your pull request.

Ps! A logo would be nice as well.

Thanks,

//Daniel

Developer that lives by the mantra "code is meant to be shared".

Comments