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

Property or Function?

I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How do
you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into a
property and what should be a function?
Apr 8 '06 #1
27 5595
Do you have any specific information that makes you think that you can't or
shouldn't do this sort of thing in a property?

In my view, a property can be considered to be a'kin to an adjective (a
describing word) and a method can be considered to be a'kin to a verb (an
action word).

Taking, as an example, an animal class, it might have a boolean property
'EatsGrass' and a method 'EatGrass'. The former 'describes' whether or not
the animal does eat grass while the latter instructs the animal to carry out
the 'action' eat grass.

Sometimes the distinction between whether to implement something as a
property or a method can be subtle and sometimes it can simply be a matter
of choice.

In your case, it is clear that you have a collection (Things) of Thing
objects. While each Thing object has a Duration property, the Things
collection has a Duration property being the sum of the Duration properties
of it's members.

In this case the use of a property is valid because Duration describes
something about the collection of Thing objects.
"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How
do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into
a property and what should be a function?

Apr 8 '06 #2
In this particular example I would chose a function over a property.
The reason is because a lot (most?) people assume that properties are
constant time operations. They may repeated call the property without
realizing the performance effect it may have.

If you still think it makes since to make it a property then at least
document that runtime is linear and not constant.

Also, I believe the Framework Design Guidelines book in the Microsoft
..NET Development Series recommends keeping the runtime of properties
constant.

Brian

sklett wrote:
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How do
you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into a
property and what should be a function?


Apr 8 '06 #3

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How
do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into
a property and what should be a function?
I don't know about any guidlines but "information hiding" can be a double
edged sword. In my view "get" without "set" works very well with reference
types but confuses things when used to return values.

David

Apr 8 '06 #4
"sklett" <sk****@mddirect.com> wrote:
And it made me think... "Is that OK to do stuff" in a property?" and "How do
you decide to use a property or a function?"


In your example, my instinct would be to memo-ize it -- i.e. keep a
private nullable field which is the lazy result of the computation,
and when you call the "get" method it computes the answer if necessary
and stores it in that nullable field as a side-effect (so can be
retrieved later), and also have a central "Invalidate" field which
re-zeroes all such nullable fields upon any possibly-change-causing
set.

What this has done, of course, is turn a one-line piece of code into a
sixty-line object...

--
Lucian
Apr 8 '06 #5
How so?

A readonly property is natural e.g. Drink.IsLiquid - A drink, by definition
is liquid so what point would there be in the IsLiquid property of Drink
being updateable?

Also, by there very nature, properties are self-documenting, i.e., a
property with a get accessor but no set accessor is readonly, a property
with a set accessor but no get accessor is writeonly and a property with
both accessors is read/write.

It is not a matter of 'information hiding'. It is a matter of providing the
appropriate functionality to solve the problem at hand.
"David" <Co*********@AdsorptionProcessModeling.com> wrote in message
news:LQDZf.301$iF3.190@dukeread01...

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How
do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into
a property and what should be a function?


I don't know about any guidlines but "information hiding" can be a double
edged sword. In my view "get" without "set" works very well with reference
types but confuses things when used to return values.

David


Apr 8 '06 #6
Lucian Wischik <lu***@wischik.com> wrote:
retrieved later), and also have a central "Invalidate" field which
re-zeroes all such nullable fields upon any possibly-change-causing


I meant, "a central protected Invalidate method" which is called by
all your relevant setter methods.

--
Lucian
Apr 8 '06 #7
> In this particular example I would chose a function over a property.
The reason is because a lot (most?) people assume that properties are
constant time operations.


I don't know about "constant time operations," but it's true that
properties shouldn't take much time to execute. That said, I have many,
many properties in the framework I built at my company that could, in
theory, go back to the database for information, so they're waaaay over
"constant time."

You see, it's not always so cut-and-dried.

On the one hand, if you make something a property, you are implying
that getting the information will be quick. So, if getting the
information is slow, that is a hint that it shouldn't be a property.

On the other hand, you don't want to determine what is a property or
not based upon implementation details. By doing so you're letting the
internal guts of how your class works leak out into its interface with
the outside world. That's bad style. So, something should be a property
if it makes sense that it be a property.

Certainly, anything that affects the state of the object in a manner
more sophisticated than just "set this to that" should be a method.
That's painfully obvious.

Similarly, an aspect of your class that can be read and set, even if
setting it does more than just set a variable, should probably be a
property. Reasonably straightfoward.

However, sometimes the two design goals above-properties that return
results quickly and not letting implementation determine
interface-are at odds with each other, and you have to make a
judgement call.

In the case of my system, I had things that logically should be
properties (from an interface point of view) but the object held only
keys, not references to the objects themselves, so the "get" on the
property has to fetch the object in question from the database. It was
an open question whether to code:

Supplier theSupplier = stockItem.Supplier;

or

Supplier theSupplier = stockItem.GetSupplier();

I chose the former, preferring to hide the implementation (holding
supplier UID, not supplier itself) rather than let it leak out that
getting the supplier was actually a lot of work. In our case it's no
problem, because we're a very small shop. In a different situation I
might have gone for door #2.

In your case, I would definitely make it a property. The fact that you
have to loop through some stuff is an implementation detail and, as
Lucian pointed out, you could always cache the result to avoid
recalculating it the second and subsequent times. You might even be
able to keep the "answer" up to date internally as your object is
modified.

That's why the design guideline about not choosing property / method
based on implementation is there: because next month you may think of a
different implementation that is much faster, but you've already made
it a method when it would have made more sense as a property.

Apr 8 '06 #8
Drink.IsLiquid - has much value: my beer is warm; I stick it in the freezer
to cool down quickly and forget; now Drink.IsLiquid returns false.

Chris
Beware of dragons: to them you are a crunchy snack and taste good with
ketchup
"Stephany Young" <noone@localhost> wrote in message
news:ue**************@TK2MSFTNGP05.phx.gbl...
How so?

A readonly property is natural e.g. Drink.IsLiquid - A drink, by
definition is liquid so what point would there be in the IsLiquid property
of Drink being updateable?

Also, by there very nature, properties are self-documenting, i.e., a
property with a get accessor but no set accessor is readonly, a property
with a set accessor but no get accessor is writeonly and a property with
both accessors is read/write.

It is not a matter of 'information hiding'. It is a matter of providing
the appropriate functionality to solve the problem at hand.
"David" <Co*********@AdsorptionProcessModeling.com> wrote in message
news:LQDZf.301$iF3.190@dukeread01...

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and
"How do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes
into a property and what should be a function?


I don't know about any guidlines but "information hiding" can be a double
edged sword. In my view "get" without "set" works very well with
reference types but confuses things when used to return values.

David



Apr 8 '06 #9
I would go back to OO first principles: what is the 'isness' of the object?
If you suspect your property is doing "too much" that could be a clue that
your object is fuzzy around the edges (not sure if it's one thing or
another).

A second principle I would apply (I just thought of it as I was perusing the
posts, so have never actually tested it in a real situation) is this:
setting or getting any property should not alter the value of any other
property. Calling a method can be expected to alter the values of any or all
of the object's properties - and naturally the method's behavior can be
expected to vary depending on the properties' values at the time it was
called.

Depending on your application's threadiness, or interaction with physical
devices (otherwise known as 'volatile' addresses [hmm - not sure if the
'volatile' keyword made its way into C# from C/C++]) there may be necessary
actions to take when getting/setting a property. This, I would consider, to
be valid behavior in an accessor function.

Here's another keyword from C++ that I'm not sure exists in C# (need to read
up some, I can see :): "mutable" - meaning a data member that can be changed
even if the object is otherwise required to be const. A mutable data member
might be a reference counter, for example - that is related to the
management of the object, not its value. Accessor methods can probably be
safely expected to touch mutable data members in order for their operation
to be complete.

HTH,
Chris
"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How
do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into
a property and what should be a function?

Apr 8 '06 #10
Tha's a spurious argument because now it's ice, it's not Drink any more -
rather it is Not Drink.

<s> wrote in message news:cd********************@comcast.com...
Drink.IsLiquid - has much value: my beer is warm; I stick it in the
freezer to cool down quickly and forget; now Drink.IsLiquid returns false.

Chris
Beware of dragons: to them you are a crunchy snack and taste good with
ketchup
"Stephany Young" <noone@localhost> wrote in message
news:ue**************@TK2MSFTNGP05.phx.gbl...
How so?

A readonly property is natural e.g. Drink.IsLiquid - A drink, by
definition is liquid so what point would there be in the IsLiquid
property of Drink being updateable?

Also, by there very nature, properties are self-documenting, i.e., a
property with a get accessor but no set accessor is readonly, a property
with a set accessor but no get accessor is writeonly and a property with
both accessors is read/write.

It is not a matter of 'information hiding'. It is a matter of providing
the appropriate functionality to solve the problem at hand.
"David" <Co*********@AdsorptionProcessModeling.com> wrote in message
news:LQDZf.301$iF3.190@dukeread01...

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and
"How do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes
into a property and what should be a function?

I don't know about any guidlines but "information hiding" can be a
double edged sword. In my view "get" without "set" works very well with
reference types but confuses things when used to return values.

David



Apr 8 '06 #11
<<s>> wrote:
Drink.IsLiquid - has much value: my beer is warm; I stick it in the freezer
to cool down quickly and forget; now Drink.IsLiquid returns false.


That's fine - but Stephany asked the point of it being *updateable*. I
would suggest that in this case you wouldn't tell the drink that it was
no longer liquid, but perhaps tell it its temperature and let it decide
when it becomes solid.

--
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
Apr 8 '06 #12
<<s>> wrote:
I would go back to OO first principles: what is the 'isness' of the object?
If you suspect your property is doing "too much" that could be a clue that
your object is fuzzy around the edges (not sure if it's one thing or
another).

A second principle I would apply (I just thought of it as I was perusing the
posts, so have never actually tested it in a real situation) is this:
setting or getting any property should not alter the value of any other
property. Calling a method can be expected to alter the values of any or all
of the object's properties - and naturally the method's behavior can be
expected to vary depending on the properties' values at the time it was
called.
I'm not sure I agree with that. It makes sense that if you set one
property, it shouldn't change another *writable* property, but I don't
think it's a problem to affect a readonly property. For instance, a
rectangle might have orthogonal settable Width and Height properties,
but setting those properties could affect the readonly Area property. I
don't think that's a problem, and in many cases it is positively
beneficial.
Depending on your application's threadiness, or interaction with physical
devices (otherwise known as 'volatile' addresses [hmm - not sure if the
'volatile' keyword made its way into C# from C/C++])


It did, but with somewhat different semantics.

--
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
Apr 8 '06 #13
As one can see in this thread there is many ways to look at this.

In my teaching I present this problem area as

Property: Hold data
Methods: Manipulate(/process) data

Now the question come as you have, what about computed properties. Well as
someone state here, properties should be fast in execution. As a user of
your class expect the property to have a "value" and should be able to
retrieve this value in a "fast" manner. So the question is how can you
return this value fast.

Compute it on access of pre-compute it.

In your case you have compute on access and this might be ok for this case.

You could have changed it and computed this value every time a "thing" is
added to the "things". Making it pre-computed, and get a fast access of the
property.

What way to choice, well I would say it is different from case to case. (
and programmer :-) )

/cjw
"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How
do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into
a property and what should be a function?

Apr 8 '06 #14

"Stephany Young" <noone@localhost> wrote in message
news:ue**************@TK2MSFTNGP05.phx.gbl...
How so?
In the example given the duration was calculated. Calculate is a verb.
Calculating duration within a get accessor hides the fact that it needs to
be calculated without providing the benifit of simplifying the code. It's
information misleading rather than information hiding.

A readonly property is natural e.g. Drink.IsLiquid - A drink, by
definition is liquid so what point would there be in the IsLiquid property
of Drink being updateable?

Also, by there very nature, properties are self-documenting, i.e., a
property with a get accessor but no set accessor is readonly, a property
with a set accessor but no get accessor is writeonly and a property with
both accessors is read/write.

It is not a matter of 'information hiding'. It is a matter of providing
the appropriate functionality to solve the problem at hand.
"David" <Co*********@AdsorptionProcessModeling.com> wrote in message
news:LQDZf.301$iF3.190@dukeread01...

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and
"How do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes
into a property and what should be a function?


I don't know about any guidlines but "information hiding" can be a double
edged sword. In my view "get" without "set" works very well with
reference types but confuses things when used to return values.

David



Apr 8 '06 #15
Who cares if the Duration was calculated or not. All the consumer needs to
know that when the property is 'queried' it returns the value. The consumer
has absolutely no need to know how the functionality is implemented.

That is the beauty of the whole concept.

Next you'll have use back to directly manipulating registers!
"David" <Co*********@AdsorptionProcessModeling.com> wrote in message
news:2yNZf.312$iF3.64@dukeread01...

"Stephany Young" <noone@localhost> wrote in message
news:ue**************@TK2MSFTNGP05.phx.gbl...
How so?


In the example given the duration was calculated. Calculate is a verb.
Calculating duration within a get accessor hides the fact that it needs to
be calculated without providing the benifit of simplifying the code. It's
information misleading rather than information hiding.

A readonly property is natural e.g. Drink.IsLiquid - A drink, by
definition is liquid so what point would there be in the IsLiquid
property of Drink being updateable?

Also, by there very nature, properties are self-documenting, i.e., a
property with a get accessor but no set accessor is readonly, a property
with a set accessor but no get accessor is writeonly and a property with
both accessors is read/write.

It is not a matter of 'information hiding'. It is a matter of providing
the appropriate functionality to solve the problem at hand.
"David" <Co*********@AdsorptionProcessModeling.com> wrote in message
news:LQDZf.301$iF3.190@dukeread01...

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and
"How do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes
into a property and what should be a function?

I don't know about any guidlines but "information hiding" can be a
double edged sword. In my view "get" without "set" works very well with
reference types but confuses things when used to return values.

David



Apr 8 '06 #16
David <Co*********@AdsorptionProcessModeling.com> wrote:
How so?


In the example given the duration was calculated. Calculate is a verb.
Calculating duration within a get accessor hides the fact that it needs to
be calculated without providing the benifit of simplifying the code. It's
information misleading rather than information hiding.


It's only misleading if you regard properties as being restricted to
just returning values without doing any calculations at all.

What counts as a calculation, anyway? If an indexer needs to access
another collection in order to return a value, does that count as a
calculation? What about multiplying two fields (eg width and height) to
return an area?

While I agree that a member being a property implies there won't be
*very* much calculation involved, I wouldn't want to restrict myself to
only things which required no calculations. Examples of things from the
framework which wouldn't be properties in that case:

String.Length
FileStream.Length
FileStream.Name
FileStream.Position
Pretty much all the DateTime properties
Most of the Type properties
Most of the Environment properties
etc

Would you rather they weren't properties?

--
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
Apr 8 '06 #17

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How
do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into
a property and what should be a function?


It's not OK regardless of the time complexity or semantics of the class.
It's not OK because it is uint and uint is not CLS compliant.

Regarding the other arguments:
Don't use a property if it is going to take significant time to calculate.
That is what people expect and it is wrong to say that it shouldn't matter -
nobodyuses a property or method thinking "well this might take 10ms or 3
hours but who cares". Theoretically you could document its time behaviour
but we all know that that is not going to work well in practice. Having a
user cache the value of a property just seems wrong and as for whoever it
was who said that their class might go to the database to get a property
value I just wouldn't want to work with their software.

If number of Thing can be large then I'd go for the keeping track of it
rather than calculating afresh each time or providing a method.
Apr 8 '06 #18
Nick,

Fortunately for both of us you don't have to work with my software, nor
I with yours. :-)

I don't recommend writing a property that has to head off to the
database. It was an experimental thing which hasn't caused us any
problems here because the few of us working here understand what's
involved. It's become a "local idiom," if you will. The first access is
slow; all subsequent accesses are lightning fast.

However, in retrospect, I would probably have made these methods, even
though it (unfortunately) leaks information about the implementation
into the interface. Certainly I would make them methods if our software
were ever to be used outside our tiny shop.

We're going to rewrite the whole thing soon anyway... the first effort
was a throwaway.

Anyway, that was an extreme example. The point was (and still stands)
that it's sometimes not a simple thing to decide between method and
property. O-O principles tell us "don't expose implementation details
in your public interface," while sensible .NET convention tells us
"properties should execute quickly." Sometimes those two goals are at
odds and you have to weigh each one off against the other.

"A property can never do any calculations" is silly, just as "a
property can do anything it likes" is silly. The truth is somewhere in
between.

Apr 9 '06 #19
I think that the controversy has chiefly stemmed from the fact that the
emphasis here has been misplaced. The emphasis of this thread has been on
what a property should or should not *do.* In fact, I believe the
controversy can be avoided altogether (by reasonable minds) by shifting the
emphasis to what a property *is*. This is OOP, and OOP is all about
abstraction. A property is called a "property" because it represents a
"property of an object." Now, we all know that an object is not really an
object, but an abstraction of an encapsulation of process and data that are
treated as part of the same "thing" in order to make it easier for us
humans, who more naturally think abstractly about almost everything, to work
with that process and data. We all know what the word "property" has meant
since long before it was used in programming terms: " A characteristic trait
or peculiarity, especially one serving to define or describe its possessor."
Like the words "class," "type," and "object," the word "property" was
employed to describe the abstraction that the programming definition of
"property" represents.

In the same vein, the word "method" is defined in the English language as "A
means or manner of procedure, especially a regular and systematic way of
accomplishing something." Therefore, the appellations of these 2 terms
should tend to indicate when each rule should be employed. The confusion
arises because in programming, a property has a get and/or set "method" to
return the "value" of the property. However, is this not true in real life
as well? For example, a human being has a "property" called "weight." How is
the weight known? It is not stored as a number somewhere in the person. It
is obtained by a "method" which employs using a measuring device of some
kind to weigh the person.

Of course, in the realm of programming, as in real life, it is not optimal
to calculate any property every time the state is required. Some properties
are stored, and calculated less often, to save processor work. The same can
be said of real-life properties. Does a person step on a scale every time
their weight is requested of them? No, they weigh themselves occasionally,
and report the results, which are accurate enough for general purposes, but
may not be exact, when asked. If an accurate measurement is required, the
person can step onto the scales again, executing the "method" by which the
"property" is obtained.

In other words, a "property" in programming is appropriate for use in
obtaining what can be abstractly termed as "a characteristic or trait" of an
object, while a "method" is appropriate for use when describing a "means or
manner of procedure." That is, regardless of what sort of calculation may be
involved, it is the abstraction which is important. Creating a property for
any method that takes no arguments would be silly. Creating a method for any
process that is required to obtain data is equally silly. The only "correct"
definition is that for which the terms were originally employed - as
abstractions in an abstract paradigm.

I hope this serves to put out those flames.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Show me your certification without works,
and I'll show my certification
*by* my works.

"Bruce Wood" <br*******@canada.com> wrote in message
news:11**********************@g10g2000cwb.googlegr oups.com...
Nick,

Fortunately for both of us you don't have to work with my software, nor
I with yours. :-)

I don't recommend writing a property that has to head off to the
database. It was an experimental thing which hasn't caused us any
problems here because the few of us working here understand what's
involved. It's become a "local idiom," if you will. The first access is
slow; all subsequent accesses are lightning fast.

However, in retrospect, I would probably have made these methods, even
though it (unfortunately) leaks information about the implementation
into the interface. Certainly I would make them methods if our software
were ever to be used outside our tiny shop.

We're going to rewrite the whole thing soon anyway... the first effort
was a throwaway.

Anyway, that was an extreme example. The point was (and still stands)
that it's sometimes not a simple thing to decide between method and
property. O-O principles tell us "don't expose implementation details
in your public interface," while sensible .NET convention tells us
"properties should execute quickly." Sometimes those two goals are at
odds and you have to weigh each one off against the other.

"A property can never do any calculations" is silly, just as "a
property can do anything it likes" is silly. The truth is somewhere in
between.

Apr 9 '06 #20
Bruce Wood wrote:
In this particular example I would chose a function over a property.
The reason is because a lot (most?) people assume that properties are
constant time operations.


I don't know about "constant time operations," but it's true that
properties shouldn't take much time to execute. That said, I have many,
many properties in the framework I built at my company that could, in
theory, go back to the database for information, so they're waaaay over
"constant time."

You see, it's not always so cut-and-dried.


Oh yeah. I completely agree. Another example of where I would bend
the rule is lazy initialization or singletons.

Apr 9 '06 #21
wow, good times! ;0)

I think I will leave it. I read everyones various takes on things, some I
agree with more than others. As far as times goes, this is a FAST process
so I'm not concerned with that. Keeping an additional member with the
precalculated duration isn't appealing as I would need to add a type and an
"Add()" method to my class, I would also need to have a "Remove()" method.

Nice to see everyones opinions though, also nice to see that there isn't a
cut and dry answer.
Enjoy your Sundays!

-SK

"sklett" <sk****@mddirect.com> wrote in message
news:OL*************@TK2MSFTNGP05.phx.gbl...
I just found myself doing something I haven't before:
<code>
public uint Duration
{
get
{
uint duration = 0;
foreach(Thing t in m_things)
{
duration += t.Duration;
}

return duration;
}
}
</code>

And it made me think... "Is that OK to do stuff" in a property?" and "How
do you decide to use a property or a function?"

So, that's my question: Are there guidelines for deciding what goes into
a property and what should be a function?

Apr 9 '06 #22

"Brian Gideon" <br*********@yahoo.com> wrote in message
news:11**********************@v46g2000cwv.googlegr oups.com...
Bruce Wood wrote:
> In this particular example I would chose a function over a property.
> The reason is because a lot (most?) people assume that properties are
> constant time operations.


I don't know about "constant time operations," but it's true that
properties shouldn't take much time to execute. That said, I have many,
many properties in the framework I built at my company that could, in
theory, go back to the database for information, so they're waaaay over
"constant time."

You see, it's not always so cut-and-dried.


Oh yeah. I completely agree. Another example of where I would bend
the rule is lazy initialization or singletons.


There are particular problems with lazy initialization and accessing remote
data:-

I think that one thing that most people would agree about properties is that
they don't expect them to throw exceptions.

IMHO this rules out accessing any remote data source in a property since
there are just too many ways that it can fail that are not the fault of the
application.

This can be a problem for any property but it is particularly unexpected
with singletons and lazy initialization.

Apr 10 '06 #23

Nick Hounsome wrote:
There are particular problems with lazy initialization and accessing remote
data:-

I think that one thing that most people would agree about properties is that
they don't expect them to throw exceptions.

IMHO this rules out accessing any remote data source in a property since
there are just too many ways that it can fail that are not the fault of the
application.

This can be a problem for any property but it is particularly unexpected
with singletons and lazy initialization.


Yes. On second thought singletons might not be a good situation to
bend the rules. Some of the same guidelines that are considered when
authoring a property apply to constructors as well. I usually avoid
long operations in constructors as does most of the .NET Framework BCL.
If you adhere to that rule then a property exposing a singleton would
be fast anyway.

Apr 10 '06 #24

"Nick Hounsome" <nh***@nickhounsome.me.uk> wrote in message
news:Ze*******************@fe2.news.blueyonder.co. uk...

I think that one thing that most people would agree about properties is that they don't expect
them to throw exceptions.


I am not sure that I agree with that.
In general the reason that most properties don't throw exceptions is that they do very little that
*could* cause an Exception. Getters are often little more than a way of making data read only. But,
just because they often don't throw exceptions, it doesn't follow that they *shouldn't* throw
Exceptions.

Almost any non-trivial settable properties will need *some* validation.

The Hashtable.Item Property throws
ArgumentNullException and
NotSupportedException
the ArrayList.Capacity Property throws
ArgumentOutOfRangeException
Even some getters throw Exceptions
the FileInfo.Length Property throws
IOException and
FileNotFoundException

the DirectoryInfo.Parent Property throws
SecurityException
Sometimes Exceptions do make sense for properties

Granted, sometimes the presence of exceptions being thrown in a property could be a signal that the
class should be rewritten.

Just my 2 cents
Bill

Apr 11 '06 #25
The no exception from properties rule generally only applies to
getters. The rule does not apply to indexers. Thats per the Framework
Design Guidelines book.

Bill Butler wrote:
"Nick Hounsome" <nh***@nickhounsome.me.uk> wrote in message
news:Ze*******************@fe2.news.blueyonder.co. uk...

I think that one thing that most people would agree about properties is that they don't expect
them to throw exceptions.


I am not sure that I agree with that.
In general the reason that most properties don't throw exceptions is that they do very little that
*could* cause an Exception. Getters are often little more than a way of making data read only. But,
just because they often don't throw exceptions, it doesn't follow that they *shouldn't* throw
Exceptions.

Almost any non-trivial settable properties will need *some* validation.

The Hashtable.Item Property throws
ArgumentNullException and
NotSupportedException
the ArrayList.Capacity Property throws
ArgumentOutOfRangeException
Even some getters throw Exceptions
the FileInfo.Length Property throws
IOException and
FileNotFoundException

the DirectoryInfo.Parent Property throws
SecurityException
Sometimes Exceptions do make sense for properties

Granted, sometimes the presence of exceptions being thrown in a property could be a signal that the
class should be rewritten.

Just my 2 cents
Bill


Apr 11 '06 #26

"Bill Butler" <qw****@asdf.com> wrote in message
news:KcC_f.8128$rm3.3969@trndny06...

"Nick Hounsome" <nh***@nickhounsome.me.uk> wrote in message
news:Ze*******************@fe2.news.blueyonder.co. uk...

I think that one thing that most people would agree about properties is
that they don't expect them to throw exceptions.
I am not sure that I agree with that.
In general the reason that most properties don't throw exceptions is that
they do very little that *could* cause an Exception. Getters are often
little more than a way of making data read only. But, just because they
often don't throw exceptions, it doesn't follow that they *shouldn't*
throw Exceptions.

Almost any non-trivial settable properties will need *some* validation.


This is a totaly different situation as the exception is caused by the
caller doing something wrong rather than the class failing its contract.

Considering only getters - it goes back to the logical meaning of a
property - it is something that you have and therefore you cannot logically
fail to return it as seems reasonable with GetX().

The Hashtable.Item Property throws
ArgumentNullException and
NotSupportedException
the ArrayList.Capacity Property throws
ArgumentOutOfRangeException
Even some getters throw Exceptions
the FileInfo.Length Property throws
IOException and
FileNotFoundException
I would say that this should not be a property and the problem is caused by
the incorrect naming. The class does not encapsulate File information it
merely provides a way to get the latest information about a file over which
it has no control.

IMHO the class should snapshot all the info and use properties (in which
case there can be no exceptions from the properties)

If you were to name the class from its behaviour it would have to be called
FileInfoAccessor or something similar and use methods.

the DirectoryInfo.Parent Property throws
SecurityException


I think that this is acceptable as it is a failure on the part of the caller
in much the same way as for a setter range exception.

To clarify: I don't think that it is acceptable for an object to say "this
is a 'property' of myself - an essential aspect of my existence and yet I
can't seem to actually find it at the moment. Sorry!"
Apr 11 '06 #27
>"Nick Hounsome" <nh***@nickhounsome.me.uk> wrote in message
news:61*********************@fe3.news.blueyonder. co.uk...
"Bill Butler" <qw****@asdf.com> wrote in message news:KcC_f.8128$rm3.3969@trndny06...

<snip>
Almost any non-trivial settable properties will need *some* validation.


This is a totaly different situation as the exception is caused by the caller doing something
wrong rather than the class failing its contract.


OK, I can agree with that.
Considering only getters - it goes back to the logical meaning of a property - it is something
that you have and therefore you cannot logically fail to return it as seems reasonable with
GetX().
As a general guideline, I agree.
Once real life and optimization rear their head, sometimes we need to bend the rules.
Suppose you have a file that consists of a bunch of fixed length records.
Each line(or group of lines) translates into an object(or heirarchy of objects).
For the sake of arguement, let's say each line is information about a person.
Ideally, you would read in the data and validate/parse it either in a helper class or in the
constructor of the person object. By the time the object is created it has everything it needs to
produce non-exception throwing properties. After all, if something were invalid we would catch it at
instantiation time.

So Far I agree with your assessment.

Now, suppose that we find that our program performs like a pig.
Here we are validating/parsing EVERY field when all we wanted to know was who was from New Jersey.
So we get the bright idea of lazy evaluation. We will only extract the properties from the text
string when it is needed.
I program perform much better BUT, now validation occurs when the property is executed and not at
instantiation time. Arguably, I could change
if (person.State == "NJ")
into
if(person.ParseState() == "NJ") // or GetState or whatever

But I would argue that the first form is much cleaner.
I could also have a Person class that had non throwing properties as well as a LazyPerson class that
implemented the same IPeson interface but could throw exceptions.

This particular sort of case has come up time and again in the work that I have done.
So, while I agree that most types of object should have non throwing properties, sometimes real life
intrudes and we need to bend the rules.
<snip>
Even some getters throw Exceptions
the FileInfo.Length Property throws
IOException and
FileNotFoundException


I would say that this should not be a property and the problem is caused by the incorrect naming.
The class does not encapsulate File information it merely provides a way to get the latest
information about a file over which it has no control.


I can understand your point, but I'm OK with it the way it is too.
IMHO the class should snapshot all the info and use properties (in which case there can be no
exceptions from the properties)

If you were to name the class from its behaviour it would have to be called FileInfoAccessor or
something similar and use methods.

the DirectoryInfo.Parent Property throws
SecurityException
I think that this is acceptable as it is a failure on the part of the caller in much the same way
as for a setter range exception.


OK, agreed
To clarify: I don't think that it is acceptable for an object to say "this is a 'property' of
myself - an essential aspect of my existence and yet I can't seem to actually find it at the
moment. Sorry!"


<grin>
Uhhhh, what was my cell phone number again???/
Damn, I never call myself.
Nick, I really don't disagree with you.
Complex exception throwing thigamajigs tend to belong in methods.
Properties in general should be quick, and locally accessible.

But I feel that it is a guideline as opposed to a rule.
You should definitely stop and think twice about your design if your getters are throwing
exceptions.
But, if the situation warrants it,....Go ahead.

Bill



Apr 12 '06 #28

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

Similar topics

3
by: Johnny M | last post by:
using Access 2003 Pardon the subject line, but I don't have a better word for this strange behavior (or behavior I don't understand!!!) I have a class module named DepreciationFactor. One of...
6
by: Cc | last post by:
hi, is there a way to use byref on property set , because i would like to pass the value into the variable byref ?
0
by: Brian Young | last post by:
Hi all. I'm using the Property Grid control in a control to manage a windows service we have developed here. The windows service runs a set of other jobs that need to be managed. The control...
0
by: Jordan Bowness | last post by:
I make a similar post in another newsgroup, but this example is simplified somewhat. I have a component (cmpMyComponent) with 2 properties. The 1st property is a string value (Description) and...
6
by: Altman | last post by:
I would like to use an indexed property to access my private array of user controls. If I don't use an indexed property, the property will show up in my Properties Window during development. Is...
15
by: Sam Kong | last post by:
Hello! I got recently intrigued with JavaScript's prototype-based object-orientation. However, I still don't understand the mechanism clearly. What's the difference between the following...
14
by: emailscotta | last post by:
Some of the object properties in the Dojo Toolkit are set to objects but they are using syntax like this: object.property = new function() { this.property = someValue; this.property =...
2
by: Lespaul36 | last post by:
I have a control that I have made that uses a custom class for storage of some of the information. I want it to display in the VS.Net 2003 property grid in the IDE like the Font property does, so...
6
by: Bob Darlington | last post by:
I want to use the caption property for fields in a recordset as a condition in a loop. That is, I only want to consider those fields which have captions: For each fld in RecordsetName.Fields If...
7
by: Computer Guru | last post by:
Hi, Pardon the unclear/verbose subject, I just can't think of another way of phrasing it. Basically, I can assign the (for instance) "Location" property of a picture box to a data-bound item....
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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...

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.