c# - Auto-implemented properties with non null guard clause? -
i agree mark seeman's notion automatic properties evil break encapsulation. concise syntax, readability , convenience bring.
i quote:
public string name { get; set; }
the problem code snippet isn’t contains ceremony. problem breaks encapsulation. in fact
“[…] getters , setters not achieve encapsulation or information hiding: language-legitimized way violate them.”
james o. coplien & gertrud bjørnvig. lean architecture. wiley. 2010. p. 134.
most of time, adding non-null guard clause enough property setter , know if there better way of doing 1 of below. better, mean in more concise/less repetitive way.
using code contracts:
private string _username; public virtual string username { { return _username; } set { contract.requires(value != null); _username = value; } }
using vanilla .net:
private string _username; public virtual string username { { return _username; } set { if (value == null) throw new argumentnullexception("username"); _username = value; } }
i'll quote code contracts manual, § 2.3.1:
public int myproperty { get; private set ; } [contractinvariantmethod] private void objectinvariant () { contract. invariant ( this.myproperty >= 0 ); ... }
Comments
Post a Comment