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;
}
}
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 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.
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 );
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With