Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-implemented properties with non null guard clause?

I do agree with Mark Seeman's notion that Automatic Properties are somewhat evil as they break encapsulation. However I do like the concise syntax, readability and convenience they bring.

I quote:

public string Name { get; set; }

The problem with the code snippet isn’t that it contains too much ceremony. The problem is that it breaks encapsulation. In fact

“[…] getters and setters do not achieve encapsulation or information hiding: they are a language-legitimized way to violate them.”

James O. Coplien & Gertrud Bjørnvig. Lean Architecture. Wiley. 2010. p. 134.

Most of the time, adding a non-null guard clause is good enough for a property setter and I would like to know if there is a better way of doing it than one of the below. By better, I mean in a more concise/less repetitive way.

Using Code Contracts:

private string _username;
public virtual string Username
{
    get { return _username; }
    set 
    {  
        Contract.Requires(value != null);
        _username = value; 
    }
}

Using vanilla .NET:

private string _username;
public virtual string Username
{
    get { return _username; }
    set 
    {
        if (value == null) throw new ArgumentNullException("Username");
        _username = value; 
    }
}
like image 972
Can Gencer Avatar asked Jul 21 '11 08:07

Can Gencer


People also ask

Which statements apply to auto implemented property?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

What is an automatic property and how is it useful?

What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it.


1 Answers

I'll just quote the Code Contracts manual, § 2.3.1:

public int MyProperty { get; private set ; }

[ContractInvariantMethod]
private void ObjectInvariant () 
{
      Contract. Invariant ( this.MyProperty >= 0 );
      ...
}
like image 172
Henk Holterman Avatar answered Sep 30 '22 05:09

Henk Holterman