A guard clause, is a check of integrity preconditions used to avoid errors during execution. It helps you to simplify code by removing useless nested branching conditions and returning meaningful errors.
To achieve it in .NET you can do it using a library or writing your own defensive code, in this article I’ll show you how to do it by using a great library called Dawn. Guard.
Let’s explore the Dawn.Guard library
Let’s say you have a user and want to do a simple validation to check if the user’s first name is not null, not empty and the length is no longer than twenty characters. Doing that without using a library, your code would look like this:
Using Guards:
If it fails it will throw an exception:
What else can I validate?
The library documentation has a full list of validations examples. You can validate strings, dates, booleans, uris, enums, emails, etc. Also, you can extend a guard condition and add your own validation.
For example, you can validate an email by creating an extension and then use it when you need to:
That’s all for now, if you want to see a full sample using it in Xamarin Forms, you can find it here.
Happy coding!
1 Comment
Great blog! I am loving it!! Will come back again. I am bookmarking your feeds also.