About today’s newsletter :
Today we are going to discuss:
What are guard clauses
How to implement them in .NET
Multiple ways of implementation
How are they different from validation
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.
🔥 Don't miss out on this exclusive opportunity to level up your coding game!
Enroll now and secure your 10% discount with coupon code : "MUWAS".
Pragmatic Clean Architecture: Learn how to confidently ship well-architected production-ready apps using clean architecture.
Whenever you’re ready, there are 2 ways I can help you
Promote yourself to 7900+ subscribers by Sponsoring my Newsletter
Become a Patron and get access to 160+ .NET Questions and Answers
As Salam alaikum sir ap ka whatsup number send kar dey