473,749 Members | 2,356 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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=val ue;}
}
Nov 16 '05 #1
18 2098
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.co m
"Janaka" <ja*****@hotmai l.com> wrote in message
news:OG******** ******@TK2MSFTN GP15.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=val ue;}
}

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(v alue)
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;
CalculateNewInc ome();
PayTaxes();
ReportToSupervi sor();
}
}

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(sal esTotal);
}
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(sal esTotal.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=val ue;}
}

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*****@hotmai l.com> wrote in message
news:OG******** ******@TK2MSFTN GP15.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=val ue;}
}

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=val ue;}
}

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*****@hotmai l.com> wrote in message
news:ew******** ******@TK2MSFTN GP12.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=val ue;}
}


Nov 16 '05 #8
James Curran <Ja*********@mv ps.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.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #9
"James Curran" <Ja*********@mv ps.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

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

Similar topics

2
3011
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, etc. After installing VS.NET 2003 everything seemed to work okay with one exception, none of the project properties appear. If I right click a project and select properties, the properties dialog appears and the property category tree is dispayed but...
4
7514
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 from the process. It occurred to me that I could also enumerate the properties of the ADO Recordset in similar fashion, expecting to get back known properties such as AbsolutePosition, BOF, EOF, Filter, Sort, etc. I inserted the following
10
7366
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 Windows.Forms.UserControl in a COM environment, i.e. I want to host that control in a COM host. So far, so good, I can host it, but I can not reach the parent COM object from the control (Parent property is null :( ). I have stopped the control in the...
6
5182
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 properties window for an Object in Active Directory. Thanks for any hints.
3
5078
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 Martin
7
8531
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 dao.property
1
1689
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 by their underlying classes (such as the TextBox control), and are not persisted by me. 2.) Unique Properties that don't map directly and are persisted in ViewState (ex.: this.LabelPosition, which specifies where on the form the label should be...
7
6069
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>(); properties.AddRange(typeof(app.IView).GetProperties());
0
2852
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 add/edit any values for a setting with type NameValueCollection. Nor can I get a NameValueCollection to persist to the User Settings via code using a simple C# Console App... Is this a user error or ?
4
9858
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 this context, in fact some articles from pre-2.0 suggest using any collection class of your choice. So my questions focus more on the syntax of event properties provided by the "event" keyword in C#. (Disclaimer - I am a C++ programmer working...
0
8996
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9388
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8256
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.