Public data members in a class is not a good design idea. When properties expose data members publicly with more control over access, properties can replace data members at every stage. Below points support the fact why properties must be preferred over public data members.
è Properties can access control even over set and
get. Few properties can only be "gettable" for other classes or only
"settable".
è Properties are first class language
elements, anything that we can do with member functions we can also do
with properties.
public
virtual string Name
{
get;
protected set;
}
è Properties are data bound to controls not the
public data members. This is as designed by framework that only Properties can
be set as data source to control's like textbox but not the public data
members.
è Properties are easier to change as to cover new
requirements or behaviors in future. e.g. We can change logic over get to
return a value only if that value's some condition is met.
è Properties can contain thread safe logic. E.g. a
setter or getter can be locked by an object to avoid multi-thread access at a
single time.
public class Customer
{
private object syncHandle = new object();
private string name;
public string Name
{
get
{
lock (syncHandle)
return name;
}
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException(
"Name cannot be blank",
"Name");
lock (syncHandle)
name = value;
}
}
è Properties can do basic validation on the data
before set or data. This avoids us from adding validation logic throughout the
code when we access that data.
è Properties can be Virtual. They are allowed to
be overridden unlike public data members.
è Properties can be abstract and also can be part
of interface.
è Properties can be parameterized . e.g. while
implementing indexers, Properties will accept index to return item at that
index.
public Address this[string name]
{
get { return adressValues[name]; }
set { adressValues[name] = value; }
}
è Properties can invoke
other methods in Set or Get just like from any other member method.
There can be many other advantages of Properties
which we find out while coding.
References: Book - Effective C# - Version 4
No comments:
Post a Comment