473,804 Members | 2,034 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 5650
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****@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 9 '06 #22

"Brian Gideon" <br*********@ya hoo.com> wrote in message
news:11******** **************@ v46g2000cwv.goo glegroups.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***@nickhoun some.me.uk> wrote in message
news:Ze******** ***********@fe2 .news.blueyonde r.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
ArgumentNullExc eption and
NotSupportedExc eption
the ArrayList.Capac ity Property throws
ArgumentOutOfRa ngeException
Even some getters throw Exceptions
the FileInfo.Length Property throws
IOException and
FileNotFoundExc eption

the DirectoryInfo.P arent Property throws
SecurityExcepti on
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***@nickhoun some.me.uk> wrote in message
news:Ze******** ***********@fe2 .news.blueyonde r.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
ArgumentNullExc eption and
NotSupportedExc eption
the ArrayList.Capac ity Property throws
ArgumentOutOfRa ngeException
Even some getters throw Exceptions
the FileInfo.Length Property throws
IOException and
FileNotFoundExc eption

the DirectoryInfo.P arent Property throws
SecurityExcepti on
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.co m> wrote in message
news:KcC_f.8128 $rm3.3969@trndn y06...

"Nick Hounsome" <nh***@nickhoun some.me.uk> wrote in message
news:Ze******** ***********@fe2 .news.blueyonde r.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
ArgumentNullExc eption and
NotSupportedExc eption
the ArrayList.Capac ity Property throws
ArgumentOutOfRa ngeException
Even some getters throw Exceptions
the FileInfo.Length Property throws
IOException and
FileNotFoundExc eption
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
FileInfoAccesso r or something similar and use methods.

the DirectoryInfo.P arent Property throws
SecurityExcepti on


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***@nickhoun some.me.uk> wrote in message
news:61******* **************@ fe3.news.blueyo nder.co.uk...
"Bill Butler" <qw****@asdf.co m> wrote in message news:KcC_f.8128 $rm3.3969@trndn y06...

<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.Parse State() == "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
FileNotFoundExc eption


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 FileInfoAccesso r or
something similar and use methods.

the DirectoryInfo.P arent Property throws
SecurityExcepti on
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
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
9591
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10594
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...
0
10343
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...
0
10087
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
7631
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
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...
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
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.