Use of properties

  • Thread starter Thread starter Paul Mcilreavy
  • Start date Start date
P

Paul Mcilreavy

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 anything that is likely to
return an error and they should not instantiate or return any big objects
etc.

My company seems to be using them for everything which is starting to cause
me concern. Any comments or other viewpoints is appreciated.
 
I think that really depends on the object in question, I don't know if it's
fair to make absolute rules.

Yes, generally properties just return values of private members. But if
that is all they ever did, there really wouldn't be much of a point to them,
would there? There are instances where a property must do some validation,
or some other processing in order to keep the object in a consistent state
given that the value of this property is being changed.

Sometimes a property needs to point to another big object, just because the
two objects are linked together and they need to talk to each other.

It's really hard to say one way or the other for a vague non specific
situation. I'm sure any construct can be misused, but in the end it all
really depends on the application and the objects involved as to what is
appropriate. At least that's my 2 cents.
 
Paul Mcilreavy said:
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 anything that is likely to
return an error and they should not instantiate or return any big objects
etc.

Well, this is bound to vary somewhat from person to person, since there are
no hard and fast rules. But my opinion as to the proper use of properties
is generally this:

* Properties are used when they can return something that is
semantically a characteristic of the object, whether static (doesn't change
during the lifetime of the object) or dynamic (may in fact change during the
lifetime of the object). If you can think of a value as somehow being tied
to the object itself, then it can be implemented as a property.

* Methods are used when one is specifically asking an object to *do*
something. This may involve returning some value, just as a property does,
or it may not. The key is that the method is used when the important thing
is the *doing*, as opposed to the *being* that a property describes.

To me, properties are nouns and adjectives related to the class, while
methods are the verbs of the class.

Note that in neither of those descriptions is there any mention of how much
effort it takes to accomplish one or the other. I would agree that
generally speaking, a property should be relatively lightweight, especially
with respect to execution time. But I don't feel this is a hard-and-fast
rule (and besides, it could also be argued that most methods should also be
relatively lightweight, especially with respect to execution time).

If semantically it makes sense for something that takes a fair amount of
work to retrieve before returning it to the caller or before changing the
state of an object (remember that properties can be retrieved, set, or both)
to still be considered a property, I think the semantics should overrule the
performance issues. After all, if you have some amount of work to be done,
it's the same whether you call it a method or a property. Imposing
artificial, implementation-related restrictions on what is essentially a
semantic question is wrong, IMHO.

As far as the question of the size of an object being returned, IMHO that's
a complete non-issue. If semantically it makes sense for a very large
object to be returned by a property, then so be it. Return it from a
property. The size of the data has nothing to do with whether something
should be a property or a method. Some methods may return a single integer
value, while some properties may return an array with tens of thousands of
elements.
My company seems to be using them for everything which is starting to
cause me concern. Any comments or other viewpoints is appreciated.

You should be concerned if properties are being used for literally
*everything*. But not for the reasons you suggest.

Pete
 
Hi, i would like to get some view points on the use of properties

Properties are best avoided. They seem great at first, but in fact they
obscure your code. Suddenly there is a third kind of class member, data,
functions (methods) and now, NEW NEW NEW, properties. My experience is, when
I want to get some value, I use Get...(), when I want to set something, I
use Set...(value); Then you know where to look for what happens.
 
yep, they would need to do some validation etc on occaision. i guess i meant
that if a property is over 10-20 lines...doing alot of validation or dealing
with big obects that can generate errors...then it should probably be a
method rather than a property
 
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 anything that is likely to
return an error and they should not instantiate or return any big objects
etc.

While it may be a religious issue, I for one strongly agree with you. It
seems likely that the language's authors even intended it this way. They
should usually provide fast, efficient and reliable access. It's cleaner and
really reflects their intended usage. Moreover, I think most people usually
assume this so if a property isn't efficient and people are frequently
calling it (perhaps in tight loops), then it can potentially have a negative
impact on your app's performance. Finally, as a purely practical issue, see
the following two links (by MSFT employees). I've experienced frustrating
problems with these issues and was personally told by a member of the VS
debugging team (Azeem Khan) that simple properties (returning member
variables only) can significantly help to avoid these problems.

http://blogs.msdn.com/greggm/archive/2005/11/18/494648.aspx
http://blogs.msdn.com/greggm/archive/2004/02/04/67766.aspx
 
Martijn said:
Properties are best avoided. They seem great at first, but in fact they
obscure your code. Suddenly there is a third kind of class member, data,
functions (methods) and now, NEW NEW NEW, properties. My experience is, when
I want to get some value, I use Get...(), when I want to set something, I
use Set...(value); Then you know where to look for what happens.

It seams that you totally missed the entire concept of object orientation.
 
I use "derived" properties at time.

Think about the age of a person. It is based on today's date , and hte dob
(date of birth ) of a person.

So ... I'll expose a "derived" property, usually readonly.



public int AgeInYears
{
get
{
return this.DeterimineAgeInYears();
}
}

private int DeterimineAgeInYears
{
if (this.m_dob != DateTime.MinDate )
{
return DateTime.Now.Substract( this.m_dob ).Years;
}
else
{
// throw new Exception("DOB was not supplied"); //<- throw an exception?
I usually don't. But its an option.
return 0;
}
}


Something along those lines.
Should I just expose the private method DeterimineAgeInYears ? Maybe? It
just depends I guess.


Sometimes I have the ".Status" property where I need to check 3 or 4 things.


But there's some food for thought. When its a "derived" property, then I do
more than just return a member variable.
At the same time, 99.8% of the time, returning a member variable is all I
do.
 
Martijn Mulder said:
Properties are best avoided. They seem great at first, but in fact
they obscure your code. Suddenly there is a third kind of class
member, data, functions (methods) and now, NEW NEW NEW, properties. My
experience is, when I want to get some value, I use Get...(), when I
want to set something, I use Set...(value); Then you know where to
look for what happens.

If you don't like properties, perhaps you should program in another
language.
Properties are an integral part of C#.

Bill
 
Hi, i would like to get some view points on the use of properties
It seams that you totally missed the entire concept of object orientation.

Totally... entire. Wow. Properties are just another way of implementing
Set...(value) and Get...() methods. In fact, the compiler substitutes
properties with methods with that signature. Totally and entire
 
It seams that you totally missed the entire concept of object orientation.

".. totally missed the entire concept of [OO]". Not. "Properties" a-la
MS Csharp (a.k.a. "not Java") is an implementation supporting the
concepts of encapsulation and information hiding - which are OO
concepts.

I agree that properties can "obscure" the code, but I do not agree that
they are "best avoided." Seems to me they are a somewhat cutesy
"we-gotta-be-different" Microsoft thing that I first saw as part of
Visual Basic's back then "kinda-sorta OO implementation" a few years
ago. Now that MS seems to be making all .NET languages exactly the
same, but different (?!) C sharp gets properties.

Yeah, they're just odd (to Java, C++, etc. programmers) "getters and
setters", and the way we tend to use them - an Uppercase spelling
(Pascal Case) of a private field, they do tend to be confusing at
times. Nonetheless I kinda like the clean synax of it.

I do think they're over-used. There really is no point in making a
field private and supplying a Property when you really want a public
field. Make the field public, duh. There is no rule that says all
fields (aka instance variables) must not be public. OTOH I think if
you have a derived value - that takes some kakulatin' - then a Property
is a neat way to make the code look like you're referencing a public
field.
 
Bob Jones said:
[...]
I agree that properties can "obscure" the code, but I do not agree that
they are "best avoided." Seems to me they are a somewhat cutesy
"we-gotta-be-different" Microsoft thing that I first saw as part of
Visual Basic's back then "kinda-sorta OO implementation" a few years ago.

For the record, VB had properties as far back as the early 90's. Not that
that's all that relevant, just thought I'd mention it. :)
[...]
I do think they're over-used. There really is no point in making a field
private and supplying a Property when you really want a public field. Make
the field public, duh.

This I disagree with wholeheartedly. One key feature of encapsulating a
field is that you control access to it. You can do range checking, and you
have the ability to in the future add logic that does other work in response
to the field changing. You can even change the underlying implementation of
the property if you like without breaking clients of the class. None of
this is possible if the field is simply a public field.

IMHO, there is no reason at all to ever make a field public. That's for
structures, not classes.

Pete
 
Martijn Mulder said:
Properties are best avoided. They seem great at first, but in fact they
obscure your code. Suddenly there is a third kind of class member, data,
functions (methods) and now, NEW NEW NEW, properties. My experience is, when
I want to get some value, I use Get...(), when I want to set something, I
use Set...(value); Then you know where to look for what happens.

Given that you should practically never be exposing fields anyway, I
don't see there's any significant difference - anything you can do with
an object *may* be doing work.

The difference is in readability - it's a lot easier to read code using
properties than setters and getters. Oh, and using your own classes
looks a lot more like using the framework classes as well, given that
they use properties extensively.
 
I do think they're over-used. There really is no point in making a
field private and supplying a Property when you really want a public
field. Make the field public, duh. There is no rule that says all
fields (aka instance variables) must not be public. OTOH I think if
you have a derived value - that takes some kakulatin' - then a Property
is a neat way to make the code look like you're referencing a public
field.

Well, there are certainly *plenty* of "guidelines" saying not to make
fields public, and plenty of reasons not to. Using fields instead of
properties:

1) You can't do validation
2) You can't *easily* break on all access/modification
3) You can't make a field read-only for everything outside the class
4) You can't change the implementation of how that essential
characteristic of the class is represented internally

Basically, it's a leaky abstraction. Too much of the implementation is
visible.

Once you've made something a field, you can't turn it into a property
without losing both source and binary compatibility. Maybe you don't
care about that, but a lot of people do.
 
fallenidol said:
yep, they would need to do some validation etc on occaision. i guess i meant
that if a property is over 10-20 lines...doing alot of validation or dealing
with big obects that can generate errors...then it should probably be a
method rather than a property

Doing a lot of validation? Not a problem, IMO.
Dealing with big objects? Not a problem, IMO.
Possibly generating errors? Not a problem, IMO - so long as it's
documented.

There's a vague expectation that property access should usually be
"pretty fast", and properties should usually be orthogonal (so changing
one property shouldn't usually change another - unless one is read-only
and solely calculated from others, eg Area from Width and Height).
 
There is no rule that says all fields (aka instance variables) must not be public.

There is to me. Or at least a very very strong suggestion not to
*until* given a good reason. Note: I have only ever found a good enough
reason twice since working with C#...

Validation
Interface implementation (interfaces can't declare fields)
Synchronisation (where needed only; not by default)
Change notification (for binding etc, or just the component model)
Consistent approach re the component model / adding a virtual (runtime)
property

But most importantly: Encapsulation: the ability to both hide and
change the implementation... if you write software that is going to be
in rolling development for a period of time with multiple developers
building on it, then you need to be able to change the internals
without affecting the contract - for instance, switching to a facade,
or moving fields into / out-of a property bag, things like that. You
can't do this with fields, and you can't rely on just switchin the
field to a property, as this is a breaking change. Even if you rebuild
the callers, "ref" usage won't work.

Marc
 
Peter, I've seen you at least once before use the analogy of properties as
adjectives and methods as verbs, and I think it's about as correct a
description to differentiate the two as possible.

A class represents a thing, a noun, and methods act on the object making
them verbs - the thing performs an action. The semantic problem with methods
as property accessors is that (in the real world) an object doesn't perform
an action to show a property of itself, e.g. a dog can perform the action of
running, but does not perform any action to show you its color. So a method
like GetColor() implies an action which doesn't really occur for a descriptor
(adjective).

Of course I'm indulging some sort of programming nirvana where types always
represent real-world things, and there aren't other factors like an
expectation of properties not performing too much(1) work, which I also agree
with, but nonetheless it's a good idiom for ideal use of properties vs.
methods.

- Ken

(1) "too much": loosley defined as "more than I think it should" ;)
 
The difference is in readability - it's a lot easier to read code using
properties than setters and getters. Oh, and using your own classes
looks a lot more like using the framework classes as well, given that
they use properties extensively.


Using properties is not a problem and indeed it looks rather neat. Writing
and maintaining your own properties does give some headache. Where, for
example, do you store them in the source file? I put fields at top, then the
constructor(s) followed by the methods, in alphabetical order. Properties
landed between the fields and the constructor, were hard to find, were hard
to maintain. It's a hybrid data type invented only to please the eye.
 
Martijn Mulder said:
Using properties is not a problem and indeed it looks rather neat. Writing
and maintaining your own properties does give some headache. Where, for
example, do you store them in the source file? I put fields at top, then the
constructor(s) followed by the methods, in alphabetical order. Properties
landed between the fields and the constructor, were hard to find, were hard
to maintain. It's a hybrid data type invented only to please the eye.

Well, I put them between the constructors and the other methods -
although I group methods by use rather than alphabetically.

I don't think it's a significant headache compared with the increase in
readability though.
 
Paul,

The only "general rule" I've ever heard was that a get property should
not change the state of an object.

A corollary would be that the set should probably only change the one
"thing" that the property refers to, although this isn't always only
one member variable.

For instance, if you have a Car object, and it's got a private Color
member variable, that's a property. Get should pretty much return the
value in the member variable, and set may do some value-add things like
make sure it's not null and check to see it's a valid color. Set
probably shouldn't change your BodyFrameType even though the
4By4Extended version isn't available in Green. Rather, it should set a
flag InvalidOptionCombination and wait for ResetValidValues(), which
will decide that 4By4Extended trumps Green and Color should be set back
to Red.

On the other hand, if you have a RecordSet object that contains a
private pointer to the current record, and there's a Read that gives
you the current record then moves the pointer to the next, Read should
be a method. By calling it, you're changing the state of the RecordSet,
so it shouldn't be a property. In this case, it also makes little sense
to have a Read property, because the whole concept of "set Read"
doesn't even make sense.

As far as performance, people generally expect properties to return
quickly. "Quickly" is purely relative: if you're reading 12GB
object-relational data structures from an Internet-distributed data
source, "lightning quick" could mean a few hours. This comes into play
most in multi-threaded scenarios: users probably want to hold a
pessimistic lock on your object while they use the property then act on
the information. If this causes them to hold a lock for a long time or
causes a deadlock, users will be unhappy.

I've also seen some peoples' coding preferences that use no properties.
These people usually wrote a lot of Java or C++ before C#. It's valid
but outdated.


Stephan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top