473,804 Members | 2,147 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
27 5651
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******** ************@co mcast.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@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 #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.co m>
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.co m>
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****@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 #14

"Stephany Young" <noone@localhos t> wrote in message
news:ue******** ******@TK2MSFTN GP05.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*********@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 #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*********@Ad sorptionProcess Modeling.com> wrote in message
news:2yNZf.312$ iF3.64@dukeread 01...

"Stephany Young" <noone@localhos t> wrote in message
news:ue******** ******@TK2MSFTN GP05.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*********@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 #16
David <Co*********@Ad sorptionProcess Modeling.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.Leng th
FileStream.Name
FileStream.Posi tion
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.co m>
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****@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?


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*******@cana da.com> wrote in message
news:11******** **************@ g10g2000cwb.goo glegroups.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

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

Similar topics

3
2501
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
9071
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
5570
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
1455
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
1876
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
1929
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
2035
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
3219
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
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10335
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
10088
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...
1
7633
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6862
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
5529
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
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
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
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.