473,796 Members | 2,688 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5649
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****@mddirec t.com> wrote in message
news:OL******** *****@TK2MSFTNG P05.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****@mddirec t.com> wrote in message
news:OL******** *****@TK2MSFTNG P05.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 "informatio n 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****@mddirec t.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*********@Ad sorptionProcess Modeling.com> wrote in message
news:LQDZf.301$ iF3.190@dukerea d01...

"sklett" <sk****@mddirec t.com> wrote in message
news:OL******** *****@TK2MSFTNG P05.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 "informatio n 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.Suppl ier;

or

Supplier theSupplier = stockItem.GetSu pplier();

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@localhos t> wrote in message
news:ue******** ******@TK2MSFTN GP05.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*********@Ad sorptionProcess Modeling.com> wrote in message
news:LQDZf.301$ iF3.190@dukerea d01...

"sklett" <sk****@mddirec t.com> wrote in message
news:OL******** *****@TK2MSFTNG P05.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 "informatio n 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****@mddirec t.com> wrote in message
news:OL******** *****@TK2MSFTNG P05.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

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

Similar topics

3
2500
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 the properties is a follows (irrelevant code omitted):
6
9069
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
5569
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 is used to view the state of the running jobs and schedule new jobs. The control also runs in the context of Internet Explorer (we do this so the administrators of the jobs can always receive the latest control). The property grid is used to...
0
1454
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 the 2nd property is a strongly typed collection class (myCollectionProperty). The collection contains a simple class (myCustomClass) which has 1 text property (TextProperty).
6
1874
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 there a way to get this to show up in the properties window?
15
1927
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 two? (1)
14
2032
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 = someFunction; } Is the property set to a new object and if so what is the "new function()" statment doing?
2
2033
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 a use can expand it and set the properties. How do I do this? Thanks in advance.
6
3216
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 fld.Properties("Caption") <"" then do something The problem is that all fields are included, even those with no caption set. I've tried IsMissing, IsEmpty and IsNull for the test but none will filter
7
1890
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. Like, I can get the absoloute location from an ADO.NET database, and assign it to the PictureBox.Location property.
0
9673
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
10221
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...
1
10169
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10003
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
9050
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
6785
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
5440
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
5569
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.