开发者

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; }
  开发者_JAVA百科  set 
    {
        if (value == null) throw new ArgumentNullException("Username");
        _username = value; 
    }
}


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 );
      ...
}


You could use aspects from PostSharp to decorate the property setter with a null check:

http://www.sharpcrafters.com/blog/post/5-Ways-That-Postsharp-Can-SOLIDify-Your-Code-Lazy-Loading-of-Dependencies.aspx

How to create an aspect checking for null references on all methods in a class in postsharp

http://magpie.sytes.net/jesperhogstrom/2010/11/compiler-safe-null-checking-of-arguments-with-aspects/


I would assume properties are just memory buffer from user point of view. only when a method (action) is invoke in user code, then checks on validity of the properties buffer should be checked (e.g., null checks throws exception).

your properties setter should place an invalid value to the internal member if data assigned is not valid (in your algorithm design). the error check and return should come from the method using this property value

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜