473,320 Members | 1,744 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,320 software developers and data experts.

Properties question

LDD
What is the real benefit of using Properties?
You can declare class variables either public/private.

I'm not sure I understand the true benefit. Especially if you are reading
from/writing to these variables
Nov 23 '05 #1
11 1212
Properties have the benefit of accessors. You have a getter and a setter
where you can put some additional logic, like raising an event to notify
subscribers that a property changed, ....

Gabriel Lozano-Morán

"LDD" <la***************@gmail.com> wrote in message
news:fv********************@magma.ca...
What is the real benefit of using Properties?
You can declare class variables either public/private.

I'm not sure I understand the true benefit. Especially if you are reading
from/writing to these variables

Nov 23 '05 #2
It's best practice to even use the Property Assessors from code private
to your class. Don't directly access your private member variables.
This protects you from forgetting that a property has code executing in
it or when you have to add code the accessor you don't have a large
refactor job.

You should not:
if (m_MyVar)

You Should:
if (MyVar)

public void MyVar
{
get{return m_MyVar;}
set{m_MyVar = value;}
}

Nov 23 '05 #3
Another reason might be to validate the data. For instance, suppose you
have a property that is an integer, but you only accept values in a certain
range. Well, before you set your private variable, you can check the value
and, maybe, throw an exception if the value is incorrect.

<mi************@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
It's best practice to even use the Property Assessors from code private
to your class. Don't directly access your private member variables.
This protects you from forgetting that a property has code executing in
it or when you have to add code the accessor you don't have a large
refactor job.

You should not:
if (m_MyVar)

You Should:
if (MyVar)

public void MyVar
{
get{return m_MyVar;}
set{m_MyVar = value;}
}

Nov 23 '05 #4
Even more, when thinking about derived classes, you cannot override the
behaviour of fields, but you can using properties. It's totally clear that a
code like the following seems to add an extra overhead when you first look
at it:

class A {
Guid id;

public Guid Id {
get {
return id;
}

set {
id = value;
}
}

If you will never change that implementation and you will never derive from
that class, well, then you may use

class A {
public Guid id;
}

But, as already said in the previous postings, if you need to check the
field content or raise events or start a thread or whatever else you may
think of when the field changes, the only way is to use a property. The most
simple example for it is a class having some fields and you want to know if
an instance of this class is dirty, meaning that one ore more properties
were modified. Using fields instead of properties, you would certainly end
up using code like the following:

class A {
public Guid Id;
public string Name;
public decimal Price;

public Guid old_Id;
public string old_Name;
public decimal old_Price;

public bool IsDirty {
get {
return (old_ID != Id && Name != old_Name && Price != old_Price);
}
}
}

If you have a class with 20 or more properties, IsDirty will become slow and
you will likely forget to add new comparisons to it when adding new fields
to the class. Furthermore you have to store two values for each field to be
able to evaluate if the instance was modified.

Compare this solution to the follwing:

class A {
public Guid id;
public string name;
public decimal price;
public bool isDirty;
public Guid Id {
get {
return id;
}

set {
if (id != value) {
id = value;
isDirty = true;
}
}

public string Name {
get {
return name;
}

set {
if (name != value) {
name = value;
isDirty = true;
}
}

public decimal Price {
get {
return price;
}

set {
if (price != value) {
price = value;
isDirty = true;
}
}

public bool IsDirty {
get {
return isDirty;
}
}
}
As you can see, there is no need to store the original values to find out if
an instance has changed. Now let's say that the price must be positive, as
you usually have to pay for everything that you can buy. If you find someone
giving you money when you buy some items, please let me know. How do you
check that with public fields? You can't. Well, you could if you have a Save
method or something similar, that checks for valid values, but the problem
is that you never know the piece of code that actually stored the invalid
value. You will only know about it when you call the Save method, which
makes finding errors a lot harder. A much better approach is the follwing:

public decimal Price {
get {
return price;
}

set {
if (price <= 0) {
throw new ArgumentException("Price must be a positive
number.");
}

if (price != value) {
price = value;
isDirty = true;
}
}
Yeah, throw an exception. Exceptions are your friend not the evil :-)

Last example: You have a class B deriving from class A and you don't want to
allow the price to be lower than 20. Can you do this check with public
fields? No, you can't. But you can with properties. Simply add the virtual
keyword to the Price property in class A:

public virtual decimal Price {
...
}

and in class B do the following:

class B : A {

public override decimal Price {
get {
return base.Price;
}

set {
if (price <= 20) {
throw new ArgumentException("Price must be at least 20
bucks.");
}

base.Price = value;
}
}
Whatever code you have implemented in class A will be executed through the
base.Price calls but you're also able to extend the logic (in this case the
comparsion >= 20).
If you still want to use public fields, go for it. Noone will stop you from
doing it and if you're very careful your application will work. However,
properties will help you in structuring your code and allow to write code at
exactly the place where it belongs. Ok, you need to add a few lines to add
the accessors, but it's worth it.

Need a last example? Try to implement a read-only field :-)
Michael
"Peter Rilling" <pe***@nospam.rilling.net> schrieb im Newsbeitrag
news:ue**************@tk2msftngp13.phx.gbl...
Another reason might be to validate the data. For instance, suppose you
have a property that is an integer, but you only accept values in a
certain range. Well, before you set your private variable, you can check
the value and, maybe, throw an exception if the value is incorrect.

<mi************@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
It's best practice to even use the Property Assessors from code private
to your class. Don't directly access your private member variables.
This protects you from forgetting that a property has code executing in
it or when you have to add code the accessor you don't have a large
refactor job.

You should not:
if (m_MyVar)

You Should:
if (MyVar)

public void MyVar
{
get{return m_MyVar;}
set{m_MyVar = value;}
}


Nov 23 '05 #5
Michael Höhne <mi************@nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you from
doing it and if you're very careful your application will work.
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

<snip>
Need a last example? Try to implement a read-only field :-)


That's easy:

public readonly int x = 10;

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #6
LDD
Thanks for the info folks.
I didn't understand why you would use properties if you could just declare
the vars as public.

My focus was on the wrong idea...

thanks again

LDD

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael Höhne <mi************@nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you from doing it and if you're very careful your application will work.
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

<snip>
Need a last example? Try to implement a read-only field :-)


That's easy:

public readonly int x = 10;

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #7
>> Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)
Agreed. If you read my reponse carefully, then you already know that I have
same opinion and that "If you still want to use public fields, go for it"
means "If you really wanna do it, do it, but it's everything else than the
recommended way."
public readonly int x = 10;

Yes, but you will not be able to modify it after assigning a value, so it
smells more like a const than a field, compared to a propertery only
exposing a get accessor.

Michael

"Jon Skeet [C# MVP]" <sk***@pobox.com> schrieb im Newsbeitrag
news:MP************************@msnews.microsoft.c om...
Michael Höhne <mi************@nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you
from
doing it and if you're very careful your application will work.
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

<snip>
Need a last example? Try to implement a read-only field :-)


That's easy:

public readonly int x = 10;

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #8
Michael Höhne <mi************@nospam.nospam> wrote:
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)
Agreed. If you read my reponse carefully, then you already know that I have
same opinion and that "If you still want to use public fields, go for it"
means "If you really wanna do it, do it, but it's everything else than the
recommended way."


:)
public readonly int x = 10;


Yes, but you will not be able to modify it after assigning a value, so it
smells more like a const than a field, compared to a propertery only
exposing a get accessor.


It's a const whose "constant value" may decided at initialisation time,
rather than the normal const which is "baked in" to any code using it.

I was really just being picky though :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 23 '05 #9
>>I was really just being picky though :)
I know :-)

"Jon Skeet [C# MVP]" <sk***@pobox.com> schrieb im Newsbeitrag
news:MP************************@msnews.microsoft.c om...
Michael Höhne <mi************@nospam.nospam> wrote:
Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)
Agreed. If you read my reponse carefully, then you already know that I
have
same opinion and that "If you still want to use public fields, go for it"
means "If you really wanna do it, do it, but it's everything else than the
recommended way."


:)
public readonly int x = 10;


Yes, but you will not be able to modify it after assigning a value, so it
smells more like a const than a field, compared to a propertery only
exposing a get accessor.


It's a const whose "constant value" may decided at initialisation time,
rather than the normal const which is "baked in" to any code using it.

I was really just being picky though :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 24 '05 #10
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael Höhne <mi************@nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you
from
doing it and if you're very careful your application will work.


Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

At my work I stop anyone trying to stop anyone from using public fields.

We had pickle before Jon, but I'll try to show what I mean one more time.

My rule:
Don't sport properties just to get/set a private field.

My argument:
A property (should) imply that the class have some knowledge about what is
valid input.
A field exlicitly says that the class have no clue.

Consider a class Person with an Age-property and Name-field.
When I as a consumer of this class uses it I would reason like this:

Hmm.. An age property. It probably checks for negative ages. And maybe it
doesn't allow for Gandalf the Wizard as he is very old. I wonder if it
throws an exception or sets bad input to min/max values. I better check the
docs for this class.

Hmm. A name field. Obviously there are no validation here and by so I better
write some code to make sure people give me somewhat proper names and not
stream a mp3 as hex into this field.

For me, properties doing nothing is like having a method named IsValid that
formats your harddrive. It's poor communication. Properties should check or
generate stuff and methods that formats harddrives should be named as such.

The exception to my rule is when you write a third-party component for
distribution to many customers, like a shareware zip utility or whatever.
For easy upgrades it is not nice to change fields into properties as your
customers might be using reflection or uses the field as a ref or out
parameter. They won't be happy if you change the public interface to your
classes as they also must refactor.

But for inhouse application classes; properties that simply maps to private
fields is just code-bloat that lies.

Happy Coding
- Michael S



Dec 1 '05 #11
Michael S <no@mail.com> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Michael Höhne <mi************@nospam.nospam> wrote:

<snip>
If you still want to use public fields, go for it. Noone will stop you
from
doing it and if you're very careful your application will work.


Hmm... if you're working professionally, and your company believes in
code reviews or pair programming, hopefully someone *will* stop you
from doing it :)

At my work I stop anyone trying to stop anyone from using public fields.

We had pickle before Jon, but I'll try to show what I mean one more time.


<snip>

I suspect we'll never agree on this, I'm afraid - for all the reasons I
gave last time. I would allow public fields for a throw-away project,
but in my experience once something has been written badly, it *tends*
to stay written badly later on, even if it means kludges elsewhere. For
instance, one person would *prefer* it to be a property, but doesn't
want to make the necessary changes elsewhere in the system (such as
when the field's being passed by reference) or isn't sure where such
changes are needed (such as if it's being found by reflection).

Your argument also seems to rely on your assumption that a property
implies processing - an assumption which seems invalid to me. After
all, you use properties for 3rd party components, so why is your
assumption invalid in that situation but valid elsewhere?

Note that changing the public interface is nasty in other situations
than just separate components that your customers will code against. If
I have 10 assemblies, all of which assume that something in one
assembly is a field, then if I want to patch that single assembly,
turning it into a property, then I have to release new versions of all
10 assemblies, rather than just providing a new version of that single
assembly.

In addition, once your team becomes used to using public fields
wherever they don't have processing, they're likely to use them even
for values which should be read-only from the outside (but mutable from
inside the class).

Keeping the rule as "never expose a non-constant field" seems much
simpler to me, and gets round all of the above. (As well as providing
other benefits such as allowing breakpoints in the property to let you
see where it's being used/changed.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 3 '05 #12

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

Similar topics

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...
3
by: cwertman | last post by:
I have a question regarding dynamic properties. I have an Object say Account --Id --Prefix --Fname --Lname --Suffix
47
by: Jon Slaughter | last post by:
private string name; public string Name { get { return name; } set { name = value; } } In the above, why doesn't C# just allow one to create a single directive to make a property?
39
by: Paul Mcilreavy | last post by:
Hi, i would like to get some view points on the use of properties within classes. My belief is that properties should generally be used to return values of private members. They should not do...
4
by: beatdream | last post by:
I am designing a database to handle different kinds of products ... and these products can have different properties...for example, a trouser can be specified by the width, length, color, and other...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.