Groups | Blog | Home
all groups > dotnet academic > february 2006 >

dotnet academic : Why not public attributes?


Joe Titanieri
2/7/2006 10:16:27 PM
Hi,

almost every book on object oriented programming does tell you, you should
not use any public attributes in a class. Instead you should provide get/set
Methods or properties (in c# for example).
I don't understand, why is it wrong to use public attributes for simple
read/write values. You would set up public get/set methods to access them
anyway in a way like this: return aValue or aValue=value.
I understand, that read only values must be protected by a get method.
Mattias Sjögren
2/8/2006 12:00:00 AM

[quoted text, click to view]

See http://en.wikipedia.org/wiki/Information_hiding


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
DWS
2/16/2006 5:55:27 PM
Joe,

Get used to it I did. Its self documenting and that is big in modern
computer applications. Checkout system.componentmodel
System.Security.Permissions for more reading.

Below I've got a property that can have only three values and is read only
at run time. It shows up in properties under behavior as dropdown list
automatically.

Sorry ! c#
imports system.componentmodel

<Category("Behavior")> _
<[ReadOnly](True)> _
Public Property FolderType() As ft
Get
Return _ftype
End Get
Set(ByVal value As ft)
_ftype = value
End Set
End Property
Public Enum ft As Integer
MyFolder = 1
Trash = 2
Simple = 0
End Enum

Don't tell anyone but the visual studio ide will fill in a complete skeleton
for a property if you just type the first line and press enter.

Good Luck
DWS


[quoted text, click to view]
Greg Young
2/28/2006 3:03:01 PM
Aside from the reason mentioned above (encapsulation) which can be summarized
by the fact that the caller does not know whether the data is coming from a
calculation or a pre-stored value; threading is another major reason we use
properties.

If I have a class such as the following.

public class Foo {
public SomeBigValueType Data;
}

I have no way of ensuring that accesses to the data member will be atomic,
by placing this in a property; I have the chance to place locking within the
getter and setter to ensure atomicity.

Greg



[quoted text, click to view]
AddThis Social Bookmark Button