Guard clauses: What are they?
Guards follow an early return strategy, quickly indicating problems by making exceptions when requirements aren't fulfilled. It is the developer's responsibility to handle these exceptions effectively in order to reduce the possibility of unexpected behaviors.
For instance, a particular requirement can be that the value—such as the connection string, encryption or decryption keys, etc.—must not be null or empty.
How are guards clauses implemented in.NET?
To do it, we have two options.
Custom terms made with the Nuget package
How should a custom guard clause be written?
To achieve what you want, create a static method inside a static class.
after which make the necessary calls.
Guard.IsNullOrEmpty(name,nameof(name)); //Call guard like this
public static class Guard
{
public static void IsNullOrEmpty(string value,string param)
{
if(string.IsNullOrEmpty(value))
{
throw new ArgumentException($"param cannot be null or empty...");
}
}
}
In this way, our code gives more readability, and instead of checking null conditions and throwing exceptions everywhere, we can do it from one place.
Using .NET libraries for guards
There are a bunch of libraries that can be helpful in this cause.
- Guard.Net
- Ardalis.GuardClauses
The second one is more famous, but I use both because of the different available methods.
Using Guard.Net
This example demonstrates how we can make a Guard for validating Regex using Guard.Net.
We can check the list of all available methods after typing Guard and dot. We can call the above validator like this.
Using Ardalis.GuardClauses
Let’s see how we can make our custom clause via this library.
On the same pattern as we did previously, we can call 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.
Best ASP.NET Core 8.0 Hosting Recommendation
At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.
0 comments:
Post a Comment