Tips on how to use guard clauses in C#



  • You should use guard clauses in your strategies to stop runtime exceptions by dealing with null reference exceptions.
  • You should use guard clauses to validate enter knowledge and implement knowledge integrity by solely processing legitimate inputs.
  • You should use guard clauses to outline preconditions on your strategies and properties, enhancing the readability and maintainability of your code.

We’ll study every of those facets of guard clauses utilizing code examples within the sections that observe.

Use a guard clause to keep away from null reference exceptions in C#

Null reference exceptions are sometimes encountered in functions once you use an object reference that has not been initialized. On this part, we are going to study how we are able to use a guard clause to stop such exceptions from being thrown at runtime. The next code snippet exhibits how one can test if the parameter of a way is null and throw an ArgumentNullException, stopping a null reference exception from being thrown at runtime and permitting the tactic to finish gracefully.


public void CheckIfNull(object obj)
{
    if (obj is null)
    {
        throw new ArgumentNullException(nameof(obj), "Methodology parameter can't be null.");
    }
    //Different code
}

Use a guard clause to implement enter validation guidelines in C#

Enter validation allows you to preserve knowledge integrity by imposing validation guidelines and constraints in your software. You possibly can implement guard clauses in your software’s supply code to permit solely legitimate knowledge to be processed by your software.

The next code instance exhibits how you need to use a guard clause in C# to stop invalid enter. Be aware how an exception is thrown if the enter string is null or empty.


public void CheckIfNullOrEmpty(string str)
{
    if(!string.IsNullOrEmpty(str))
    {
        throw new ArgumentException("Invalid knowledge: The string handed within the technique argument can't be empty or null");
    }
    //Different code
}

Use a guard clause to reinforce code readability and maintainability in C#

Guard clauses show you how to write maintainable and readable code by centralizing your software’s validation guidelines. They supply a sublime strategy to forestall sudden habits in your software’s code, making it constant, organized, and simple to keep up.

Allow us to perceive this with a code instance. Within the console software venture we created earlier, create a brand new class named Writer and enter the next code.


class Writer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Tackle { get; set; }
    public string E-mail { get; set; }
}

The next code snippet illustrates how one can benefit from the constructor of the Writer class to validate enter.


 public Writer(string firstName, string lastName, string handle, string e mail)
 {
     if (string.IsNullOrEmpty(firstName))
     {
         throw new ArgumentException("First identify can't be null or empty", nameof(firstName));
     }
     if (string.IsNullOrEmpty(lastName))
     {
         throw new ArgumentException("Final identify can't be null or empty", nameof(lastName));
     }
     if (string.IsNullOrEmpty(handle))
     {
         throw new ArgumentException("Tackle can't be null or empty", nameof(handle));
     }
     if (string.IsNullOrEmpty(e mail))
     {
         throw new ArgumentException("E-mail can't be null or empty", nameof(e mail));
     }
 }

As you possibly can see, the previous code snippet is sort of verbose. We are able to make it way more concise and readable through the use of guard clauses. Be aware that the next code can substitute all the if statements used within the constructor of the Writer class above.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *