473,796 Members | 2,864 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why simple properties?

I can understand why properties are neat if you want to limit access
(only get, no set), or you want to do some bookkeeping or sanity
checking on values (in set) or if you want to change the underlying
type without changing the property type etc.

But what is the use for properties like:

private int data;

public int Data
{
get
{
return data;
}

set
{
data = value;
}
}
?

I see this a lot. For all intents and purposes, you might just have a
public member instead. Even if you wanted to change the public member
later to a property, your interface would still be maintained. No
possibilities lost.

/David

Oct 3 '07
19 1459
On Oct 4, 3:30 pm, "Ben Voigt [C++ MVP]" <r...@nospam.no spamwrote:
No - the field's *value* is exposed, but not the field itself. I can
rename the field to my heart's content - it's an implementation
detail.

You cannot rename the public member. Fields and properties are alike in
that regard.
Yes - but it's not the same as what was claimed - that "for a read-
write property
the field is exposed to the outside".
I believe that a field is too low-level a concept to be part of the
exposed API for a well-designed component.

Even for something like System.Drawing. Point?
Yes. In fact, that's a good example - in Java, the Point class exposes
the fields directly. They are integers. When a Point with more
precision was required, a new class had to be created using doubles.
If the Point class had exposed properties instead, the existing
properties could have been kept as integers, the underlying fields
could have been changed to doubles, and new properties could have
exposed the extra precision.
What about interop structures?
They *may* be an exception, because the storage (which is usually an
implementation detail) becomes effectively part of the API. I try to
avoid interop where possible :)

Jon

Oct 4 '07 #11
FWIW: I would like to see something to make these properties less verbose;
e.g.

public property string Name;
public property int Age;
public property bool Male;

This would just be a compiler directive to create the variables name, age,
and male, as well as the get and set as usual. You could even comment it in
the usual way. This saves a HUGE amount of code and also eliminates the
potential recursive bug.

Hilton
Oct 4 '07 #12
On Oct 4, 4:08 pm, "Hilton" <nos...@nospam. comwrote:
FWIW: I would like to see something to make these properties less verbose;
e.g.

public property string Name;
public property int Age;
public property bool Male;

This would just be a compiler directive to create the variables name, age,
and male, as well as the get and set as usual. You could even comment it in
the usual way. This saves a HUGE amount of code and also eliminates the
potential recursive bug.
As I've said, C# 3 has this, but with a slightly different syntax
which avoids introducing any new keywords and still allows different
access for getters/setters. The variable itself is invisible to the
code - it can only use the property.

What C# 3 *doesn't* have (but I'd like) is a way of having custom code
in the property but still hide the variable:

public int Age
{
int age;
// Put more code in here if you want
get { return age; }
set { age = value; }
}

The compiler could still force uniqueness of variable name, but
prohibit access to the variable outside the property - possibly with
exceptions for things like serialization (with an attribute for
methods which want direct access, for instance).

That way the rest of the class is forced to use the property as well,
which aids encapsulation further.

No CLR change would be required for this, which is always nice :)

Jon

Oct 4 '07 #13
th***********@g mail.com wrote:
For a read-write property the underlying field is exposed to the
outside and there isn't any encapsulation to care about. One might as
well make the field public. This gives clearer, crisper and easier to
maintain code. The rule "Never use public fields" isn't proper
encapsulation.
I suppose that depends on your definition of "encapsulation" . But the
definition I use definitely includes "never use public fields" as a
mechanism to achieve encapsulation.

The field is an implementation detail. The property is the behavior
exposed by the class. Proper encapsulation hides implementation details
while preserving behaviors. By hiding implementation details, the class
implementation can change arbitrarily, and as long as the class
continues to provide its publicly declared behavior, there's no problem.

There is no way to change from a public field to a public property after
the fact. The difference between the field and a property is a
_behavioral_ difference, and only by changing the _behavior_ of the
class can you modify that part of the design of the class.

But if you use a property from the outset, you can modify your
implementation however you like without having to change the behavior.
This is what encapsulation is all about, and that's why never using
public fields when you can instead use a property is very much part of
proper encapsulation.
Proper encapsulation is to hide fields that are not
needed from the outside,
See, here's the fundamental difference in opinion: you believe that
encapsulation is only about "hiding" things that "are not needed from
the outside".

That's certainly one way to describe it, but it's my opinion that
encapsulation is different from that. The difference is subtle,
granted. But IMHO it's a very real difference.
but also to realize that once in a while some
internal data of an object must be exposed and public fields are a
good candidate to implement this behavior.
Well, how about that? I would agree that if "some internal data of an
object must be exposed", then you have to expose it and you have to use
public field to do that. But when does that actually happen? Can you
provide an example?

I'll start out with the obvious one: a class that is actually more like
a struct, and doesn't really have any behavior but is rather just a
place to keep data. All such a class would have is a bunch of public
fields and perhaps a constructor. I agree, no real need for properties
there.

But other than that degenerate class example, in what case is it true
that "some internal data of an object MUST be exposed"?

Pete
Oct 4 '07 #14
On 3 Okt., 11:40, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
>
No, the interface isn't maintained. There are various things you can
do with fields (such as passing them by reference) which you can't do
with properties. Likewise there are things which work with properties
(such as databinding) which don't work with fields. Anything using
reflection or serialization is likely to break as well.
Okay. Seems like kind of an random implementation artifact, and not
some deep language reason.
It's best to use properties right from the start - I don't like having
any fields which aren't private.
In situations where you just want people to be able to access the data
(in simple structs only for holding data etc.), exactly the situations
in which you would make "simple properties" as I called them, and in
which you are fairly sure that this will never change, properties are
just syntactic clutter, IMO. That might change with C# 3.0.

/David

Oct 4 '07 #15
On 4 Okt., 08:39, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Yeah, you are right. Public instance variables are very convienient,
e.g. in small struct-like classes whose only purpose is to package
some data fields. There's no need to clutter the code with endless
getters and setters.

You mean apart from proper encapsulation? Variable names are an
implementation detail, IMO.
This has nothing to do with proper encapsulation. Both solutions has
exactly the same degree of encapsulation.
Also, property names are just as much an implementation detail as is
an variable name.

/David

Oct 4 '07 #16
On 4 Okt., 16:42, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
>
Even for something like System.Drawing. Point?

Yes. In fact, that's a good example - in Java, the Point class exposes
the fields directly. They are integers. When a Point with more
precision was required, a new class had to be created using doubles.
If the Point class had exposed properties instead, the existing
properties could have been kept as integers, the underlying fields
could have been changed to doubles, and new properties could have
exposed the extra precision.
But that is precisely because of the seemingly random implementation
choice that properties must be something different than fields. I
can't see why it wouldn't be a better solution to say that a property
has the same interface as a field. Then, if the above situation
happened, you could silently change your fields to properties and
change the type of the underlying fields. I can't see how it is not a
weakness and a random implementation artifact, that this is not
possible.

/David

Oct 4 '07 #17
pi************@ gmail.com <pi************ @gmail.comwrote :
No, the interface isn't maintained. There are various things you can
do with fields (such as passing them by reference) which you can't do
with properties. Likewise there are things which work with properties
(such as databinding) which don't work with fields. Anything using
reflection or serialization is likely to break as well.

Okay. Seems like kind of an random implementation artifact, and not
some deep language reason.
Not a language reason - a design reason. What data a class chooses to
provide access to is part of the encapsulated interface. How it chooses
to store that data *should* be a hidden implementation detail. Exposing
a field exposes that implementation detail.
It's best to use properties right from the start - I don't like having
any fields which aren't private.

In situations where you just want people to be able to access the data
(in simple structs only for holding data etc.), exactly the situations
in which you would make "simple properties" as I called them, and in
which you are fairly sure that this will never change, properties are
just syntactic clutter, IMO. That might change with C# 3.0.
"Syntactic clutter" wouldn't change behaviour though, would it?
Changing a field to a property or vice versa certainly can.

--
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 4 '07 #18
pi************@ gmail.com <pi************ @gmail.comwrote :
Yeah, you are right. Public instance variables are very convienient,
e.g. in small struct-like classes whose only purpose is to package
some data fields. There's no need to clutter the code with endless
getters and setters.
You mean apart from proper encapsulation? Variable names are an
implementation detail, IMO.

This has nothing to do with proper encapsulation. Both solutions has
exactly the same degree of encapsulation.
No, they don't. Using properties, I'm hiding the implementation details
of how data is stored - or *if* it is even stored. Some properties may
be computable, for instance, or the value could be cached. If you
expose a field, you're tying the API to the fact that there's a field
of that type to store the value.
Also, property names are just as much an implementation detail as is
an variable name.
No - when all variables are private, and the properties are public, the
property names are part of the interface but the variable names are
just part of the implementation. I can change the implementation
without changing the public interface.

--
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 4 '07 #19
pi************@ gmail.com <pi************ @gmail.comwrote :
Even for something like System.Drawing. Point?
Yes. In fact, that's a good example - in Java, the Point class exposes
the fields directly. They are integers. When a Point with more
precision was required, a new class had to be created using doubles.
If the Point class had exposed properties instead, the existing
properties could have been kept as integers, the underlying fields
could have been changed to doubles, and new properties could have
exposed the extra precision.

But that is precisely because of the seemingly random implementation
choice that properties must be something different than fields. I
can't see why it wouldn't be a better solution to say that a property
has the same interface as a field. Then, if the above situation
happened, you could silently change your fields to properties and
change the type of the underlying fields. I can't see how it is not a
weakness and a random implementation artifact, that this is not
possible.
If all fields are actually properties, how could you then actually
*store* anything?

The difference between properties and fields is that properties act as
*access* and fields act as *storage*. They're not the same thing, and I
don't see any reason to treat them as the same thing.

--
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 4 '07 #20

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

Similar topics

3
1814
by: John Baro | last post by:
I have a class as: public class a : { private float m_b; public float b { get {
0
945
by: Bill O | last post by:
We have some classes with simple properties: public class StringClass {
3
1401
by: James Allen Bressem | last post by:
If you aare going to change the entire Basic language in a new distribution the least Microsoft coulds have done for VBers is give us a new simplified syntax. I have seen many cases in VB.net where they seem to have had "no insightfullness" into these considerations. Their implementation of the property for example is gaudy at best: Property Name(ByVal Value As String) As String Get
11
2554
by: Brent Ritchie | last post by:
Hello all, I have been using C# in my programming class and I have grown quite fond of C# properties. Having a method act like a variable that I can control access to is really something. As well as learning C#, I think that it's way overdue for me to start learning C++ Templates (I've been learning it for about 5 years now). I think that adding this type of functionality would be a good exercise to help learn template programming....
47
467
by: Jon Slaughter | last post by:
private string name; public string Name { get { return name; } set { name = value; } } In the above, why doesn't C# just allow one to create a single directive to make a property?
39
1952
by: Paul Mcilreavy | last post by:
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.
1
1463
by: miskomisko | last post by:
..net v2.0, VS 2005, VB6 Hi, I try to import my vb6 application to vb .net. The application uses my special activeX component which i want to import. When i import ocx file. Component is imported but not with all its properties. The property: Public Property Get Value(ByVal iRow As Long, ByVal iCol As Long) As
1
1606
by: Dunc | last post by:
Has anyone come across a way to bind simple properties (e.g. <%# DateTime.Now.Year %>, <%# UserName %in the underlying HTML) without doing a general DataBind(); call? Not only does it seem a massive waste of resources, I find this call extremely annoying, particularly when working with Master pages where inevitably I'll end up wiping out any manually build controls such as added options to dropdowns. It would be great if there was a...
1
2632
by: McMurphy | last post by:
I have a single table which I would like to search on a unique column varchar(15) that may have some nulls. Employee social club member no, some employees have a number and others don't. Those that do have a number will all have a unique number. I had added an index using: ALTER TABLE employees ADD INDEX(emp_socialclubno); However when I run: mysqlexplain select employeeid from employees where
0
9679
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9527
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
10223
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...
1
10172
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
9050
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
7546
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
5441
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
5573
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4115
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

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.