473,396 Members | 1,797 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Why use properties?

I'm having a discussion with my colleagues here on good programming
standards. One thing we haven't agreed on is the use of properties in
classes vs using member variables. Now everyone knows that it is useful to
use a property when it has to do some further action on the data such as
private double salesAvg;
public double SalesAverage
{
set {
salesAvg = value / salesTotal;
}
get {
return salesAvg;
}
}

However why is it necessary to create a property if a public member variable
will do. For example:
public int SalesTotal;

rather than

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}
Nov 16 '05 #1
18 2067
Janaka,

The best case I can think of is that you won't break your profile (which
can be a pain) when the time comes to add functionality. It's much easier
to just do this from the get go (and with the snippet template for
properties in VS.NET 2005, there is really no reason to not do it).

Ultimately, it takes control away from the developer and increases the
maintinence of this kind of code. For example, what if you derived from
this class and wanted to do some processing while setting the field?

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"Janaka" <ja*****@hotmail.com> wrote in message
news:OG**************@TK2MSFTNGP15.phx.gbl...
I'm having a discussion with my colleagues here on good programming
standards. One thing we haven't agreed on is the use of properties in
classes vs using member variables. Now everyone knows that it is useful
to use a property when it has to do some further action on the data such
as
private double salesAvg;
public double SalesAverage
{
set {
salesAvg = value / salesTotal;
}
get {
return salesAvg;
}
}

However why is it necessary to create a property if a public member
variable will do. For example:
public int SalesTotal;

rather than

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}

Nov 16 '05 #2
Janaka schrieb:
However why is it necessary to create a property if a public member
variable will do.


Publicly available member variables can be changed by anyone anytime
without the class or one of its instances taking notice about this. One
principle of OOP is the encapsulation of data.

In my class designs member variables are always declared as private.
Even descendant classes need to access my members via appropriate
properties so that the base class knows exactly what is being accessed.

Christian
Nov 16 '05 #3
Hi Janaka,

There are several reasons why properties is better than public variables.
1. It lets you filter what is entered, safeguarding against unsupported
values.

private int salesTotal;
public int SalesTotal
{
get
{
return salesTotal;
}
set
{
if(Reasonable(value)
salesTotal = value;
}
}

2. It lets you hide what actually happens (acting like a method), all the
user has to worry about is setting SalesTotal.

private int salesTotal;
public int SalesTotal
{
get
{
return salesTotal;
}
set
{
salesTotal = value;
CalculateNewIncome();
PayTaxes();
ReportToSupervisor();
}
}

3. Changes to the internals of the class won't affect any external use of
the property.

private STRING salesTotal;
public int SalesTotal
{
get
{
try
{
return Int32.Parse(salesTotal);
}
catch
{
return 0;
}
}
set
{
salesTotal = value.ToString();
}
}

4. Gives you a clean way to set and get user control values.

private TextBox salesTotal;
public int SalesTotal
{
get
{
try
{
return Int32.Parse(salesTotal.Text);
}
catch
{
return 0;
}
}
set
{
salesTotal.Text = value.ToString();
}
}

In effect, hiding the internal code is always good.
While there isn't much reason to use a property when you aren't doing
anything to the variable it is still smart to use it since you may never
know what you will do in the future.

--
Happy Coding!
Morten Wennevik [C# MVP]
Nov 16 '05 #4
On Fri, 3 Dec 2004 15:18:03 -0000, Janaka wrote:
I'm having a discussion with my colleagues here on good programming
standards. One thing we haven't agreed on is the use of properties in
classes vs using member variables.

However why is it necessary to create a property if a public member variable
will do.


In short, maintenance. Can you be absolutely sure that your member will
never need any type of manipulation either when being retrieved or when
being set? What if at some future time a requirement is added that the
member variable must be greater than 0. Would you not want to validate
that as soon as the value was set, not even allowing an invalid value? How
are you going to do that if anyone can set that member directly whenever
they wish? Or what if the value had to always be rounded to a multiple of
10. Would you want to have to do that in every place that read the value
of the variable, or would you rather code that in one place so that
everyone who read the value automatically got it rounded appropriately? By
encapsulating that member variable in get/set methods, you have protected
your code from future changes. This is good design.
--
Tom Porterfield
Nov 16 '05 #5
Another reason is that you can leverage on PropertyChanged event, very
useful. You can then propogate chain reaction to many listners to your
control.

Harshad.
"Janaka" wrote:
I'm having a discussion with my colleagues here on good programming
standards. One thing we haven't agreed on is the use of properties in
classes vs using member variables. Now everyone knows that it is useful to
use a property when it has to do some further action on the data such as
private double salesAvg;
public double SalesAverage
{
set {
salesAvg = value / salesTotal;
}
get {
return salesAvg;
}
}

However why is it necessary to create a property if a public member variable
will do. For example:
public int SalesTotal;

rather than

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}

Nov 16 '05 #6
Thanks for all the replies.

I believe the main reason why to code in a skeleton property with just a
get/set is to provide future-proofing and easier maintenance in the long
run.

Tom your reply was even approved by our head sceptic.

"Janaka" <ja*****@hotmail.com> wrote in message
news:OG**************@TK2MSFTNGP15.phx.gbl...
I'm having a discussion with my colleagues here on good programming
standards. One thing we haven't agreed on is the use of properties in
classes vs using member variables. Now everyone knows that it is useful
to use a property when it has to do some further action on the data such
as
private double salesAvg;
public double SalesAverage
{
set {
salesAvg = value / salesTotal;
}
get {
return salesAvg;
}
}

However why is it necessary to create a property if a public member
variable will do. For example:
public int SalesTotal;

rather than

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}

Nov 16 '05 #7
Funny thing is --- I was just about to post a very similar question to the
group.

However, I'm still a bit more skeptical. Of all the answers given, only
Nicholas's held water.

All the rest boil down to, "You need a property -- if you need more than
simple assignment."

But the question was, "what's the advantage of a property if all I need (for
now) is simple assignment?".

Saying
private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}

is better than

public int SalesTotal;

because I might want to change the get/set at some time in the future is a
false lead, as I could convert the latter into the former at any time.
Basically, it comes down to doing more typing now, to potentially save the
same amount of typing later. By the same principle which leads us to
lazy-loading information from databases, would lead us to prefer the public
variable until such time as we need to convert it to a Property.
--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
"Janaka" <ja*****@hotmail.com> wrote in message
news:ew**************@TK2MSFTNGP12.phx.gbl...
Thanks for all the replies.

I believe the main reason why to code in a skeleton property with just a
get/set is to provide future-proofing and easier maintenance in the long
run.

Tom your reply was even approved by our head sceptic.

public int SalesTotal;

rather than

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}


Nov 16 '05 #8
James Curran <Ja*********@mvps.org> wrote:

<snip>
Saying
<snip - property code>
is better than
<snip - field code>
because I might want to change the get/set at some time in the future is a
false lead, as I could convert the latter into the former at any time.


Yes, so long as you don't mind the change in interface. That's the key
thing - do you want to maintain interface compatibility as far as
possible, or not? I like to on principle, personally.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
"James Curran" <Ja*********@mvps.org> wrote:
Saying
[private field and accessor property]
is better than
[public field]
because I might want to change the get/set at some time
in the future is a false lead, as I could convert the latter
into the former at any time.


It might not be that simple, though. Such a change affects your
interface and forces anything using it to be recompiled. Also consider
cases with 'ref' and 'out' parameters, where using a property may not
be valid.

P.
Nov 16 '05 #10
> However why is it necessary to create a property if a public
member variable will do.


You can then use GetType().GetProperties() to dynamically discover the
properties a type supports - think property grids in the VS designer.

If something is conceptually a property, it is better to implement it as a
property. Implementing some of your properties as fields and some as
properties would be inconsistent.

This issue also touches on the whole "Component Oriented Programming" thing
that was one of the founding principles of C#.

Mark
Nov 16 '05 #11
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Yes, so long as you don't mind the change in interface. That's the key
thing - do you want to maintain interface compatibility as far as
possible, or not? I like to on principle, personally.


But... Are we changing the interface? If a class user were to write
myObject1.SalesTotal = 100.00f;
it's irrelevant to him if SalesTotal is implemented as a public variable or
as a property. Nor will he notice if it's changed. (though he will have to
recompile)

--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

Nov 16 '05 #12
James,

And that's the key. While the developer might not notice while writing
code, if they are part of the build process, they definitely will know (and
any good developer is at least compiling and testing this stuff on their
own). =)
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"James Curran" <Ja*********@mvps.org> wrote in message
news:u$******************@TK2MSFTNGP11.phx.gbl...
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Yes, so long as you don't mind the change in interface. That's the key
thing - do you want to maintain interface compatibility as far as
possible, or not? I like to on principle, personally.


But... Are we changing the interface? If a class user were to write
myObject1.SalesTotal = 100.00f;
it's irrelevant to him if SalesTotal is implemented as a public variable
or
as a property. Nor will he notice if it's changed. (though he will have to
recompile)

--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com

Nov 16 '05 #13
James Curran schrieb:
it's irrelevant to him if SalesTotal is implemented as a public variable or
as a property.


No. For instance properties can't be passed by reference.

Christian
Nov 16 '05 #14
James Curran <Ja*********@mvps.org> wrote:
Yes, so long as you don't mind the change in interface. That's the key
thing - do you want to maintain interface compatibility as far as
possible, or not? I like to on principle, personally.


But... Are we changing the interface? If a class user were to write
myObject1.SalesTotal = 100.00f;
it's irrelevant to him if SalesTotal is implemented as a public variable or
as a property. Nor will he notice if it's changed. (though he will have to
recompile)


Exactly - he'll have to recompile. It keeps the interface mostly the
same as far as the source code is concerned (see Christian's post for
an example of it breaking even that) but the interface will change at
the metadata level. That might also affect people using reflection, as
well as demanding a recompilation.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #15


"James Curran" wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Yes, so long as you don't mind the change in interface. That's the key
thing - do you want to maintain interface compatibility as far as
possible, or not? I like to on principle, personally.


But... Are we changing the interface? If a class user were to write
myObject1.SalesTotal = 100.00f;
it's irrelevant to him if SalesTotal is implemented as a public variable or
as a property. Nor will he notice if it's changed. (though he will have to
recompile)


but can you require all production code be recompiled to your changes? I
think that's rather unrealistic.
Nov 16 '05 #16
Janaka wrote:

However why is it necessary to create a property if a public member
variable
will do. For example:
public int SalesTotal;

rather than

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}


And we got sensible answers, in particular: if you later have to change your
public member variable into a property because get and set become more
complex, you'll have to recompile all calling code.

And, to have your code consistend, you should not mix properties and public
member variables.

OK, so it makes sense to use properties. But why are public member variables
even allowed then? What might be a reason to consider using them?

Joachim
Nov 16 '05 #17
Here is the rule of thumb we use:

- If a public instance member in an assembly, especially one to be reused by
outside users, always go for a property.

- If an internal Type in an assembly, determine if there are some good
reasons before making a property (error checking, centralization of logic
are good reasons). These will be compiled every time anyway, so the
"recompile" argument doesn't hold.

- If a private Type only used by one other enclosing Type, prefer a public
field, unless there is some other good reason (centralization of logic).
This is the most likely situation where you might use a public field, for
example on an internal lightweight struct definition. The struct used as a
hashtable bucket is a good example.

- Static readonly data may be faster if presented as a public const field.

So there are uses for public fields. If you don't need a property, you can
save a bit of code. But the uses are rare.

Regards,
Frank Hileman

check out VG.net: http://www.vgdotnet.com
Animated vector graphics system
Integrated Visual Studio .NET graphics editor
"Joachim Pense" <sp************@pense-online.de> wrote in message
news:co*************@news.t-online.com...
Janaka wrote:

However why is it necessary to create a property if a public member
variable
will do. For example:
public int SalesTotal;

rather than

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}


And we got sensible answers, in particular: if you later have to change
your
public member variable into a property because get and set become more
complex, you'll have to recompile all calling code.

And, to have your code consistend, you should not mix properties and
public
member variables.

OK, so it makes sense to use properties. But why are public member
variables
even allowed then? What might be a reason to consider using them?

Joachim

Nov 16 '05 #18
On Fri, 3 Dec 2004 12:13:10 -0500, James Curran wrote:
But the question was, "what's the advantage of a property if all I need (for
now) is simple assignment?".

private int salesTotal;
public int SalesTotal
{
get {return salesTotal;}
set {salesTotal=value;}
}

is better than

public int SalesTotal;

because I might want to change the get/set at some time in the future is a
false lead, as I could convert the latter into the former at any time.


Can you do it so easily? You are thinking in a very closed minded manner.
Do you assume that everyone who uses your class will be a language that
hides the actual get/set methods of a property behind direct access? Yes,
in C# if you code a property with a get and set then you can access that
directly via Class.Property. Not all languages support that. In some that
may appear instead as Class.get_Property and Class.set_Property. You will
have already forced a recompile of anyone who uses your object. For those
using a language other than C# or VB you may have also forced them to
change their code. Good design dictates encapsulating access to member
variables through properties. The amount of extra work is extremely small
and the payoff in maintenance is potentially substantial.

Along the same lines I have seen recommendations that you should never
write a public constructor for any of your objects. You should leave the
constructor of your object private, and add a static method that returns an
instance of your object. This would mean that anyone who uses your object
would have to ask you specifically for that instance. The reasoning for
this is again to protect against future modifications that you can not
anticipate today. For example, possibly in some future scenario you end up
with several forms of your object, each coded for a variation of the
scenario for which the first was coded. By coding a method that returns an
instance of your object rather than allowing it to be created directly you
now have control of which variation of your object to return. If the
variations get rather numbered, you can easily delegate the instance
creating method to a factory object that at initial development was not
even considered.

Food for thought.
--
Tom Porterfield
Nov 16 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Rick Austin | last post by:
I recently had to perform a reinstalltion of Windows XP (my registry seems to have become corrupt). After this completed I had to reinstall all applications since most use the registry for settings,...
4
by: Lyn | last post by:
Hi, This question may seem a bit academic... To learn more about Access VBA, I have been enumerating the properties of various form controls. This was mostly successful and I have learned a lot...
10
by: Sunny | last post by:
Hi, I have an old problem which I couldn't solve so far. Now I have found a post in that group that gave me an idea, but I can not fully understand it. The problem is: I'm trying to use a...
6
by: JerryP | last post by:
Hello, is there a way to launch the property dialogue for a directory from my c# app ? I would also like to launch the User Account Properties from Active Directory Users and Computers, and the...
3
by: Martin Montgomery | last post by:
I have, for example, a property called myProperty. I would like, when using a property grid to display the property name as "My Property". Is this possible. Is there an attribute etc Thank ...
7
by: Donald Grove | last post by:
Is it possible to retrieve field properties from a table in access2000 using code? I have tried: " dim dbs as dao.database dim tbl as dao.tabledef dim fld as dao.field dim prop as...
1
by: Christophe Peillet | last post by:
I have a CompositeControl with two types of properties: 1.) Mapped Properties that map directly to a child control's properties (ex.: this.TextboxText = m_txt.Text). These properties are handled...
7
by: Anderskj | last post by:
Hi! I am developing a c# application. I have a interface (which can change therefore my problem) If i do like this: List<PropertyInfoproperties = new List<PropertyInfo>();...
0
by: =?Utf-8?B?UmljayBHbG9z?= | last post by:
For some unknown reason (user error?), I cannot get a NameValueCollection to persist in the app.config file. Unlike other settings, I cannot get the String Collection Editor GUI to allow my to...
4
by: FullBandwidth | last post by:
I have been perusing various blogs and MSDN pages discussing the use of event properties and the EventHandlerList class. I don't believe there's anything special about the EventHandlerList class in...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.