property vs field

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,
Can you please explain from your experience on why
accessing data members through properties is a better
practice than accessing data members themselves? I still
am having a hard time understanding the advantages of
properties and the downside of writing code in other ways.
Thanks a lot. I appreciate your valuable replies.
 
In short ... properties are like methods ... you can control the values
assigned to the associated variable....you can also provide read only or
write only access ... or both ...

where as regular variables you cannot ... you need separate functions for
get and set ....

in properties its all in one place ...
 
Hi all,
Can you please explain from your experience on why
accessing data members through properties is a better
practice than accessing data members themselves? I still
am having a hard time understanding the advantages of
properties and the downside of writing code in other ways.
Thanks a lot. I appreciate your valuable replies.

1) You might need to validate before allowing access to the member;
example:

public string Something
{
set
{
if (value != String.Empty) {
something = value;
}
}
}

2) Even if you don't need to do the above right *now*, you may need to
in future. In this case, if you used a property all along, you can
simply change the code in the property accessors.

3) Even if you'll /never/ need to do the above, it's consistent to
always use properties; else you might end up with a situation like:

class Foo
{
public int a;
private bool b; // uses property for access
public int c;
private bool d; // uses property for access
}

Consistency is a key part of code readability!

4) Even if all of your members don't need properties for access, it's
still the /standard/ thing to do.
 
Can you please explain from your experience on why
accessing data members through properties is a better
practice than accessing data members themselves? I still
am having a hard time understanding the advantages of
properties and the downside of writing code in other ways.
Thanks a lot. I appreciate your valuable replies.

1) You have more control - you can restrict access so that people can
read but not write, only write certain values, etc.

2) You can easily trace when people are reading and writing.

3) You can later migrate to (say) change the type of the field (but not
property), read it from a database, compute it etc, all without
changing your interface.
 
Back
Top