What are guard clauses
Guards adhere to an early return policy, promptly signaling issues through exceptions when conditions are not met. The obligation lies with the developer to appropriately handle these exceptions, mitigating the risk of unintended behaviors.
For example: a specific condition could be that value should not be null or empty e.g. connection string, encryption or decryption keys etc.
How to implement guards clauses in .NET
We have two ways to do that :
-
Custom clauses
-
Using nuget package
How to write custom guard clause
Make a static method in a static class for your desired purpose.
And then call it wherever needed.
In this way our code gives more readability and instead of checking null condition and throwing exception everywhere we can do it from one place.
Using .NET libraries for guards
There are bunch of libraries that can be helpful in this cause :
-
Guard.Net
-
Ardalis.GuardClauses
Second one is more famous but I use both because of different available methods.
Using Guard.Net
This example demonstrates how can we make a Guard for validating Regex using Guard.Net We can check list of all available methods after typing Guard and dot.
We can call above validator like this :
Using Ardalis.GuardClauses
Let’s see how can we make our custom clause via this library :
On same pattern as we did previously we can call this like this
How are they different from validation
Guards and validation serve different roles in development.
Guards quickly stop the program and throw an exception if something unexpected happens. It’s like a safety net that developers need to handle when things go wrong.
Validation, on the other hand, carefully checks all the data in a model, making detailed error messages for anything that doesn’t fit. It’s great for making sure the data follows the rules of the business.
In short, guards stop problems early, while validation is good for making sure everything fits the plan.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place