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

Why use properties?

I see tons of examples where people use properties where the get and set
correspond directly to a single variable in a class. If this is the case, why
not just access the variable directly? Is it an encapsulation issue? This
seems strange since there's often no restriction applied at the level of the
property. Just curoius...

-Ben
Nov 21 '05 #1
20 8279
Hi Ben,

It is a good OOP practice. You may want to perform some validation before
setting a value or perform some other action, or set different access levels
to the get/set accessors (not possible yet in .NET 1.0/1.1). Even if none of
this applies yet, the code is prepared for future changes. It becomes an
habit, so you see a lot of code like that.

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com

"Ben R." <be**@newsgroup.nospam> escribió en el mensaje
news:71**********************************@microsof t.com...
I see tons of examples where people use properties where the get and set
correspond directly to a single variable in a class. If this is the case,
why
not just access the variable directly? Is it an encapsulation issue? This
seems strange since there's often no restriction applied at the level of
the
property. Just curoius...

-Ben

Nov 21 '05 #2
encapsulation and validation are some issues. you may also need to set
contingent/dependant variables/properties based on a parent property or run
a method when it is set or even raise different events based on its new
value.

it is a good habit to set up properties in this fashion since it is often
the case that your needs/requirements will change as your application
evolves...scalability should always be a consideration. and for maintanence
purposes, being consistent means being less prone to error and more clear in
intent.

hth,

steve
"Ben R." <be**@newsgroup.nospam> wrote in message
news:71**********************************@microsof t.com...
|I see tons of examples where people use properties where the get and set
| correspond directly to a single variable in a class. If this is the case,
why
| not just access the variable directly? Is it an encapsulation issue? This
| seems strange since there's often no restriction applied at the level of
the
| property. Just curoius...
|
| -Ben
Nov 21 '05 #3

"Ben R." <be**@newsgroup.nospam> wrote in message
news:71**********************************@microsof t.com...
I see tons of examples where people use properties where the get and set
correspond directly to a single variable in a class. If this is the case,
why
not just access the variable directly? Is it an encapsulation issue? This
seems strange since there's often no restriction applied at the level of
the
property. Just curoius...

-Ben


To go along with all the other suggestions, I have a question for your
question:

Why not?

Mythran

Nov 21 '05 #4
Because it's less code to type? ;-)

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com

"Mythran" <ki********@hotmail.comREMOVETRAIL> escribió en el mensaje
news:Oq*************@TK2MSFTNGP15.phx.gbl...

To go along with all the other suggestions, I have a question for your
question:

Why not?

Mythran

Nov 21 '05 #5


Ben R. wrote:
I see tons of examples where people use properties where the get and set
correspond directly to a single variable in a class. If this is the case, why
not just access the variable directly? Is it an encapsulation issue? This
seems strange since there's often no restriction applied at the level of the
property. Just curoius...


It's a good habit to get into. Agreed, in a quick-n-dirty project you
might feel you can 'get away' with Public instance variables, but it
only takes a few cases of wanting to validate new values, or wanting to
change the underlying data type without changing the contract, or
wanting to track reads, before you start always wrapping stuff in
properties.

It can seem sometimes like the old joke about using Math.Pi instead of
3.14 (*), but really it takes very little time to do, and as I said
once you've got into the habit you will thank yourself innumerable
times.

--
Larry Lard
Replies to group please

Nov 21 '05 #6
Ben,

As probably you I am never interested in answers as why not.

A property is very useful with binding
A property is very useful when you use a property grid as is standard with
the IDE
A property is very useful when you have to convert a value for internal use
in the class (and than encapsulate the how)
A property is very usuful when you want to test if it fulfils a condition
and than throw an exception in that procedure

Probably there are a lot more, however to give some

That is needed for OOP is for me bs. I really don't use it in a simple
loginform to transport the data. For that is the value for me good enough,

I find as well the argument from Carlos very valid. (Before you get a wrong
idea, I use normally properties, however as I wrote it is for me not forever
a must.)

However, only my opinion.

Cor
Nov 21 '05 #7

"Carlos J. Quintero [.NET MVP]" <ca*****@NOSPAMsogecable.com> wrote in
message news:Oo*************@TK2MSFTNGP10.phx.gbl...
Because it's less code to type? ;-)

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com

"Mythran" <ki********@hotmail.comREMOVETRAIL> escribió en el mensaje
news:Oq*************@TK2MSFTNGP15.phx.gbl...

To go along with all the other suggestions, I have a question for your
question:

Why not?

Mythran



That works! :)

Mythran

Nov 21 '05 #8

"Cor Ligthert" <no************@planet.nl> wrote in message
news:Ou*************@TK2MSFTNGP09.phx.gbl...
Ben,

As probably you I am never interested in answers as why not.

A property is very useful with binding
A property is very useful when you use a property grid as is standard with
the IDE
A property is very useful when you have to convert a value for internal
use in the class (and than encapsulate the how)
A property is very usuful when you want to test if it fulfils a condition
and than throw an exception in that procedure

Probably there are a lot more, however to give some

That is needed for OOP is for me bs. I really don't use it in a simple
loginform to transport the data. For that is the value for me good enough,

I find as well the argument from Carlos very valid. (Before you get a
wrong idea, I use normally properties, however as I wrote it is for me not
forever a must.)

However, only my opinion.

Cor


I'm still relatively new to VB.NET, but another point that I know of with
respect to properties is that you can make them read-only or write-only. If
your class is going to be part of an add-in used by other programmers, you
would have to write extra code to protect your public variables if you
wanted them read/write only. Is this not correct?

Dave
Nov 21 '05 #9
Ben,
In addition to the other comments.

I use properties as they Encapsulate the field. Some features, such as the
PropertyGrid requires them.

Remember that Encapsulation is one of the tenets of Object Oriented
Programming.

Also I may have properties that are not based on fields, having some
properties & some fields feels like (smells like) an "Oddball Solution", an
"Oddball Solution" is when you have two or more similar constructs (public
Properties & public Fields) done two or more different ways (public
Properties & public Fields). "Oddball Solution" is a "code smell" that is
identified in "Refactoring to Patterns"
http://www.industriallogic.com/xp/refactoring/.
Here are a couple of blogs that make a good case against using Properties:

http://blogs.msdn.com/jaybaz_ms/arch...29/123333.aspx

http://blogs.msdn.com/ericgu/archive...29/123588.aspx

Hope this helps
Jay

"Ben R." <be**@newsgroup.nospam> wrote in message
news:71**********************************@microsof t.com...
|I see tons of examples where people use properties where the get and set
| correspond directly to a single variable in a class. If this is the case,
why
| not just access the variable directly? Is it an encapsulation issue? This
| seems strange since there's often no restriction applied at the level of
the
| property. Just curoius...
|
| -Ben
Nov 21 '05 #10
David,
You can make fields readonly also, readonly fields can only be set in the
constructor.

Something like:

Public Class Person

Public Readonly Name As String

Public Sub New(ByVal name As String)
Me.Name = name
End Sub

End Class

I will make private fields Readonly also if the field is not intended to be
modified elsewhere in my class, to ensure anyone who inherits my code knows
that the field does not change...

Something like:

Public Class Person

Private ReadOnly m_name As String

Public Sub New(ByVal name As String)
m_Name = name
End Sub

Public ReadOnly Property Name() As String
Get
Return m_name
End Get
End Property

End Class

Of course readonly properties with read/write fields are useful also. For
example SqlConnection.State, the SqlConnection.Open, SqlConnection.Close, &
other methods change the SqlConnection.State Property, however you cannot
set the SqlConnection.State to a specific value.

Hope this helps
Jay
"David Lee Conley"
<no***************************@nospamearthlink.net .nospam> wrote in message
news:6G*****************@newsread2.news.atl.earthl ink.net...
|
| "Cor Ligthert" <no************@planet.nl> wrote in message
| news:Ou*************@TK2MSFTNGP09.phx.gbl...
| > Ben,
| >
| > As probably you I am never interested in answers as why not.
| >
| > A property is very useful with binding
| > A property is very useful when you use a property grid as is standard
with
| > the IDE
| > A property is very useful when you have to convert a value for internal
| > use in the class (and than encapsulate the how)
| > A property is very usuful when you want to test if it fulfils a
condition
| > and than throw an exception in that procedure
| >
| > Probably there are a lot more, however to give some
| >
| > That is needed for OOP is for me bs. I really don't use it in a simple
| > loginform to transport the data. For that is the value for me good
enough,
| >
| > I find as well the argument from Carlos very valid. (Before you get a
| > wrong idea, I use normally properties, however as I wrote it is for me
not
| > forever a must.)
| >
| > However, only my opinion.
| >
| > Cor
| >
|
| I'm still relatively new to VB.NET, but another point that I know of with
| respect to properties is that you can make them read-only or write-only.
If
| your class is going to be part of an add-in used by other programmers, you
| would have to write extra code to protect your public variables if you
| wanted them read/write only. Is this not correct?
|
| Dave
|
|
Nov 21 '05 #11
David,

Partially correct however a very good point; read only.

Cor
Nov 21 '05 #12
Hi ! :O)

In addition to others comment, it also makes your class consistent with the
other classes of the Framework, which in my opinion is a must.
This simplifies things a bit when coding some generic function using
Reflection (i.e. PropertyInfo vs FieldInfo)...

--
Best Regards
Yanick
"Ben R." <be**@newsgroup.nospam> a écrit dans le message de
news:71**********************************@microsof t.com...
I see tons of examples where people use properties where the get and set
correspond directly to a single variable in a class. If this is the case, why not just access the variable directly? Is it an encapsulation issue? This
seems strange since there's often no restriction applied at the level of the property. Just curoius...

-Ben

Nov 21 '05 #13
Maybe I'm missing something but;

Public Class myClass
Public myField as Integer
....
End Class

Is less typing than:

Public Class myClass
Private myPropertySave as Integer
Public Property myProperty () as Integer
Get
myProperty = myPropertySave
End Get
Put (Value as Integer)
myPropertySave = Value
End Put
End Class

--
Dennis in Houston
"Carlos J. Quintero [.NET MVP]" wrote:
Because it's less code to type? ;-)

--

Best regards,

Carlos J. Quintero

MZ-Tools: Productivity add-ins for Visual Studio .NET, VB6, VB5 and VBA
You can code, design and document much faster.
Free resources for add-in developers:
http://www.mztools.com

"Mythran" <ki********@hotmail.comREMOVETRAIL> escribió en el mensaje
news:Oq*************@TK2MSFTNGP15.phx.gbl...

To go along with all the other suggestions, I have a question for your
question:

Why not?

Mythran


Nov 21 '05 #14
Dennis,
Maybe I'm missing something but;

Because it's less code to type? ;-)

--

In my opinion gave Carlos a correct answer on the question "Why not".

For the rest there are not much advantages for "Why not". Although it is in
the part where OOP has some overhead, although I will be the last to give
that as a significant reason.

Cor
Nov 21 '05 #15
Properties are just "convenience methods" for you, the programmer.

The language compiler you use has to translate the properties set/get to
get_property and set_property methods.

The property name and info is still preserved in the assembly for other
purposes.
Best Regards
Alejandro Lapeyre

"Cor Ligthert" <no************@planet.nl> escribió en el mensaje
news:uG**************@tk2msftngp13.phx.gbl...
Dennis,
Maybe I'm missing something but;

Because it's less code to type? ;-)

--

In my opinion gave Carlos a correct answer on the question "Why not".

For the rest there are not much advantages for "Why not". Although it is
in the part where OOP has some overhead, although I will be the last to
give that as a significant reason.

Cor

Nov 21 '05 #16
"Dennis" <De****@discussions.microsoft.com> wrote in message
news:A0**********************************@microsof t.com...
Maybe I'm missing something but; .. . . Public myField as Integer
Is less typing

.. . .

Well, yes - it is.
But it should be the exception that a Property Set routine should be
so "trusting". Every class you write should be downright paranoid
about what "Things" in the "Outside World" are going to try and do
to it.

As an example, say you have a class that mimics a ComboBox and
you expose an updateable SelectedIndex property. At any point in
time, this *must* point to a valid item in your "list" or be set to -1,
indicating that no item is selected.

In this case, you *have* to check the value you are being given,
something like

Private m_iSelIndex as Integer = -1

Public Property SelectedIndex () as Integer

Get
Return m_iSelIndex
End Get

Put (Value as Integer)
Select Case Value
Case m_iSelIndex
' Same value as we had before
' Do Nothing

Case 0 to m_oInnerList.Count - 1
' A new, different, Value - save it ...
m_iSelIndex = Value

' ... and notify anyone who cares by raising
' the SelectedIndexChanged Event
Me.OnSelectedIndexChanged()

Case Else
' Invalid value for this property.
' We could default (and suppress) this ...
m_iSelIndex = -1

' ... or we could be more "demonstrative"
Throw New ArgumentException( ...

End Select
End Put
End Property

HTH,
Phill W.
Nov 21 '05 #17
"Carlos J. Quintero [.NET MVP]"
<ca*****@NOSPAMsogecable.com>'s wild thoughts were released
on Wed, 15 Jun 2005 17:58:11 +0200 bearing the following
fruit:
Because it's less code to type? ;-)


You could type that 'less code' and then your just a right
click away from 'convert field to property'...... ;-)

Jan Hyde (VB MVP)

--
Advertisement: What gets people on the brandwagon. (Robert Meyers)

[Abolish the TV Licence - http://www.tvlicensing.biz/]

Nov 21 '05 #18
Or maybe the New Procedure Assistant? ;-)

Best regards,

Carlos J. Quintero

"Jan Hyde" <St***********@REMOVE.ME.uboot.com> escribió en el mensaje
news:n9********************************@4ax.com...

You could type that 'less code' and then your just a right
click away from 'convert field to property'...... ;-)

Jan Hyde (VB MVP)

Nov 21 '05 #19

"Mythran" <ki********@hotmail.comREMOVETRAIL> wrote in message
news:Oq*************@TK2MSFTNGP15.phx.gbl...

"Ben R." <be**@newsgroup.nospam> wrote in message
news:71**********************************@microsof t.com...
I see tons of examples where people use properties where the get and set
correspond directly to a single variable in a class. If this is the case,
why
not just access the variable directly? Is it an encapsulation issue? This
seems strange since there's often no restriction applied at the level of
the
property. Just curoius...

-Ben


To go along with all the other suggestions, I have a question for your
question:

Why not?

Mythran


Everyone took this question wrong...I think..

I was asking why not... emphasis on "asking". I have heard arguments both
ways and besides "typing less code", I haven't seen a really good reason why
not. Typing less code could be interpreted as "laziness". I'm not trying
to offend those that stated or agreed with it, but it is one interpretation
of "typing less code".

I didn't really mean "Why not?" as an answer, but I could understand why it
would have been taken that way.

Anywho, regardless of the point behind my question, I believe my question
was partially answered. I also read up on some of the posted links that
refer to Extreme Programming. Those links, in my opinion, don't necessarily
apply in particular to properties vs fields, but instead to a general rule
of thumb regarding doing more than you have to at the present time. I do
agree with those rules, but not for properties vs fields 100% of the time.

Just my 2¼¢ :)

Mythran

Nov 21 '05 #20
Mythran,

Everyone took this question wrong...I think..

Absolute not to offend you and not personal meant, just for fun.

In my country is told that one fool can ask more than ten wise man can
answer.

:-))

Cor

Nov 21 '05 #21

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

Similar topics

2
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,...
4
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...
10
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...
6
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...
3
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 ...
7
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...
1
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...
7
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>();...
0
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...
4
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...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.