Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method argument validation of complex types

I'm a fan of argument validation in methods. Something like this is commonly seen in my code:

public void Foo(string someString)
{
    #region parameter validation
    if(string.IsNullOrWhiteSpace(someString))
        throw new ArgumentNullException("someString");
        // Let's ignore the .NET 4.6 nameof-feature for the sake of this question.
    #endregion

    // do things
}

Now let's say the method doesn't accept a string, but a complex object. Let's say I want the method to validate whether a property of this complex object is set. What would be the correct way to do this? Up until now I've done it like this:

public void Foo(Person person)
{
    #region parameter validation
    if(person == null)
        throw new ArgumentNullException("person");
    if(string.IsNullOrWhiteSpace(person.Name))
        throw new ArgumentNullException("person.Name");
    #endregion

    // do things
}

Is there some best practice for this? Is ArgumentNullException the correct way to go? Is checking properties like this even recommended?

like image 519
Daniel Schmid Avatar asked Apr 01 '26 18:04

Daniel Schmid


1 Answers

In my case, all my models have a Validate method, this way I just call it and if it returns false (which means I got errors) I call another method to get the errors from it and display to the user, something like this:

if (person == null)
    throw new ArgumentNullException (nameof (person));

// Validates only 1 property.
if (!person.Validate (nameof (person.MyProperty)))
    DisplayErrors (person);

// Validates all properties.
if (!person.Validate ())
    DisplayErrors (person);

The reason behind it is that in most cases I have to allow the model to be invalid while the user is filling the information. I use these method with the interface INotifyDataErrorInfo for WPF to enable the UI to refresh when errors occur.

When only part of object is required for a method or operation, a facade model is the solution where you create a new class that envelopes your more complex one, and the facade class have the Validate method too to do partial validation.

like image 68
Alexandre Borela Avatar answered Apr 04 '26 07:04

Alexandre Borela