473,804 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Use of properties

Hi, i would like to get some view points on the use of properties within
classes. My belief is that properties should generally be used to return
values of private members. They should not do anything that is likely to
return an error and they should not instantiate or return any big objects
etc.

My company seems to be using them for everything which is starting to cause
me concern. Any comments or other viewpoints is appreciated.
Oct 24 '06
39 1953
On 2006-10-24 15:54:18 -0500, Göran Andersson <gu***@guffa.co msaid:
Martijn Mulder wrote:
>>Hi, i would like to get some view points on the use of properties

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

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

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

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

I do think they're over-used. There really is no point in making a
field private and supplying a Property when you really want a public
field. Make the field public, duh. There is no rule that says all
fields (aka instance variables) must not be public. OTOH I think if
you have a derived value - that takes some kakulatin' - then a Property
is a neat way to make the code look like you're referencing a public
field.

Oct 25 '06 #11
"Bob Jones" <ro****@jonesho use.comwrote in message
news:2006102422 000350073%rober t@joneshousecom ...
[...]
I agree that properties can "obscure" the code, but I do not agree that
they are "best avoided." Seems to me they are a somewhat cutesy
"we-gotta-be-different" Microsoft thing that I first saw as part of
Visual Basic's back then "kinda-sorta OO implementation" a few years ago.
For the record, VB had properties as far back as the early 90's. Not that
that's all that relevant, just thought I'd mention it. :)
[...]
I do think they're over-used. There really is no point in making a field
private and supplying a Property when you really want a public field. Make
the field public, duh.
This I disagree with wholeheartedly. One key feature of encapsulating a
field is that you control access to it. You can do range checking, and you
have the ability to in the future add logic that does other work in response
to the field changing. You can even change the underlying implementation of
the property if you like without breaking clients of the class. None of
this is possible if the field is simply a public field.

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

Pete
Oct 25 '06 #12
Martijn Mulder <i@mwrote:
Hi, i would like to get some view points on the use of properties

Properties are best avoided. They seem great at first, but in fact they
obscure your code. Suddenly there is a third kind of class member, data,
functions (methods) and now, NEW NEW NEW, properties. My experience is, when
I want to get some value, I use Get...(), when I want to set something, I
use Set...(value); Then you know where to look for what happens.
Given that you should practically never be exposing fields anyway, I
don't see there's any significant difference - anything you can do with
an object *may* be doing work.

The difference is in readability - it's a lot easier to read code using
properties than setters and getters. Oh, and using your own classes
looks a lot more like using the framework classes as well, given that
they use properties extensively.

--
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
Oct 25 '06 #13
Bob Jones <ro****@jonesho use.comwrote:

<snip>
I do think they're over-used. There really is no point in making a
field private and supplying a Property when you really want a public
field. Make the field public, duh. There is no rule that says all
fields (aka instance variables) must not be public. OTOH I think if
you have a derived value - that takes some kakulatin' - then a Property
is a neat way to make the code look like you're referencing a public
field.
Well, there are certainly *plenty* of "guidelines " saying not to make
fields public, and plenty of reasons not to. Using fields instead of
properties:

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

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

Once you've made something a field, you can't turn it into a property
without losing both source and binary compatibility. Maybe you don't
care about that, but a lot of people do.

--
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
Oct 25 '06 #14
fallenidol <fa********@dis cussions.micros oft.comwrote:
yep, they would need to do some validation etc on occaision. i guess i meant
that if a property is over 10-20 lines...doing alot of validation or dealing
with big obects that can generate errors...then it should probably be a
method rather than a property
Doing a lot of validation? Not a problem, IMO.
Dealing with big objects? Not a problem, IMO.
Possibly generating errors? Not a problem, IMO - so long as it's
documented.

There's a vague expectation that property access should usually be
"pretty fast", and properties should usually be orthogonal (so changing
one property shouldn't usually change another - unless one is read-only
and solely calculated from others, eg Area from Width and Height).

--
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
Oct 25 '06 #15
There is no rule that says all fields (aka instance variables) must not be public.

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

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

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

Marc

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

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

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

- Ken

(1) "too much": loosley defined as "more than I think it should" ;)

"Peter Duniho" wrote:
"Paul Mcilreavy" <fa********@dis cussions.micros oft.comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Hi, i would like to get some view points on the use of properties within
classes. My belief is that properties should generally be used to return
values of private members. They should not do anything that is likely to
return an error and they should not instantiate or return any big objects
etc.

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

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

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

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

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

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

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

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

Pete
Oct 25 '06 #17
The difference is in readability - it's a lot easier to read code using
properties than setters and getters. Oh, and using your own classes
looks a lot more like using the framework classes as well, given that
they use properties extensively.

Using properties is not a problem and indeed it looks rather neat. Writing
and maintaining your own properties does give some headache. Where, for
example, do you store them in the source file? I put fields at top, then the
constructor(s) followed by the methods, in alphabetical order. Properties
landed between the fields and the constructor, were hard to find, were hard
to maintain. It's a hybrid data type invented only to please the eye.
Oct 25 '06 #18
Martijn Mulder <i@mwrote:
The difference is in readability - it's a lot easier to read code using
properties than setters and getters. Oh, and using your own classes
looks a lot more like using the framework classes as well, given that
they use properties extensively.

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

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

--
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
Oct 25 '06 #19
Paul,

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

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

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

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

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

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

Paul Mcilreavy wrote:
Hi, i would like to get some view points on the use of properties within
classes. My belief is that properties should generally be used to return
values of private members. They should not do anything that is likely to
return an error and they should not instantiate or return any big objects
etc.

My company seems to be using them for everything which is starting to cause
me concern. Any comments or other viewpoints is appreciated.
Oct 25 '06 #20

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

Similar topics

2
3016
by: Rick Austin | last post by:
I recently had to perform a reinstalltion of Windows XP (my registry seems to have become corrupt). After this completed I had to reinstall all applications since most use the registry for settings, etc. After installing VS.NET 2003 everything seemed to work okay with one exception, none of the project properties appear. If I right click a project and select properties, the properties dialog appears and the property category tree is dispayed but...
4
7517
by: Lyn | last post by:
Hi, This question may seem a bit academic... To learn more about Access VBA, I have been enumerating the properties of various form controls. This was mostly successful and I have learned a lot from the process. It occurred to me that I could also enumerate the properties of the ADO Recordset in similar fashion, expecting to get back known properties such as AbsolutePosition, BOF, EOF, Filter, Sort, etc. I inserted the following
10
7375
by: Sunny | last post by:
Hi, I have an old problem which I couldn't solve so far. Now I have found a post in that group that gave me an idea, but I can not fully understand it. The problem is: I'm trying to use a Windows.Forms.UserControl in a COM environment, i.e. I want to host that control in a COM host. So far, so good, I can host it, but I can not reach the parent COM object from the control (Parent property is null :( ). I have stopped the control in the...
6
5187
by: JerryP | last post by:
Hello, is there a way to launch the property dialogue for a directory from my c# app ? I would also like to launch the User Account Properties from Active Directory Users and Computers, and the properties window for an Object in Active Directory. Thanks for any hints.
3
5079
by: Martin Montgomery | last post by:
I have, for example, a property called myProperty. I would like, when using a property grid to display the property name as "My Property". Is this possible. Is there an attribute etc Thank Martin
7
8537
by: Donald Grove | last post by:
Is it possible to retrieve field properties from a table in access2000 using code? I have tried: " dim dbs as dao.database dim tbl as dao.tabledef dim fld as dao.field dim prop as dao.property
1
1694
by: Christophe Peillet | last post by:
I have a CompositeControl with two types of properties: 1.) Mapped Properties that map directly to a child control's properties (ex.: this.TextboxText = m_txt.Text). These properties are handled by their underlying classes (such as the TextBox control), and are not persisted by me. 2.) Unique Properties that don't map directly and are persisted in ViewState (ex.: this.LabelPosition, which specifies where on the form the label should be...
7
6072
by: Anderskj | last post by:
Hi! I am developing a c# application. I have a interface (which can change therefore my problem) If i do like this: List<PropertyInfoproperties = new List<PropertyInfo>(); properties.AddRange(typeof(app.IView).GetProperties());
0
2854
by: =?Utf-8?B?UmljayBHbG9z?= | last post by:
For some unknown reason (user error?), I cannot get a NameValueCollection to persist in the app.config file. Unlike other settings, I cannot get the String Collection Editor GUI to allow my to add/edit any values for a setting with type NameValueCollection. Nor can I get a NameValueCollection to persist to the User Settings via code using a simple C# Console App... Is this a user error or ?
4
9865
by: FullBandwidth | last post by:
I have been perusing various blogs and MSDN pages discussing the use of event properties and the EventHandlerList class. I don't believe there's anything special about the EventHandlerList class in this context, in fact some articles from pre-2.0 suggest using any collection class of your choice. So my questions focus more on the syntax of event properties provided by the "event" keyword in C#. (Disclaimer - I am a C++ programmer working...
0
9594
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
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...
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
10089
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
9171
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...
1
7634
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
5530
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...
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.