fields or properties

  • Thread starter Thread starter julien
  • Start date Start date
J

julien

Hello,
I don't know when to use fields and when to used properties. It looks to
me that using properties is always better. But I guess fields must be
better in some cases, otherwise they wouldn't exist!

Thank you
Julien
 
Well, lets see. I think maybe you are confused about the difference between
them as they are very different things. The easiest way to answer this
would be with an example I guess.

When you write a class you more times than not need variables to hold data
in order for the class to operate correctly. These variables that are
defined in the class are known as fields. They are really nothing more than
variables defined in the class to hold data in order for the class to work
its magic.

However, there is a major problem with exposing these variables(fields) to
the user of the class. Just because you are writing the class and
understand how its suppose to work, doesn't mean the guy next year that
creates an instance of your class will understand all the inner workings of
it.

So when you lay out your class and one of the fields named "CustPhone" needs
to always be formatted like: 111-111-1111, you can't be sure the guy using
your class or even you will remember that later on.

In comes properties. Properties are really not variables at all, but are
rather functions that handle writing and reading from your internal
variables or fields. By using the Set and Get features of properties you
are now able to control what gets written to and read from your internal
fields, keeping the users of your classes from being able to enter corrupt
data into the class that might cause failure later down the road.

Hopefully that helps you understand the difference. Fields and Properties
are always used together and should really be in most class designs, unless
you have no real reason to provide a property to access a field. But the
fields are always there no matter what as a property is useless if it has
nothing to write to.

Good luck and I hope I understood your question.

glenn
 
julien said:
So, fields should be private only and properties public?

Yes - although properties don't have to be public, either. It can often
be useful to have internal, protected or even private properties.
 
Fields should be private or protected. In a good OO architecture there is no
real reason for a feild to ever be public.

Protected feilds are valid because they can be used by derived classes but
your architecture should be designed with the pro's and cons of allowing
derived classes access to base feilds.

Making a field public breaks the rules of encapsulation because it allows
external code to modify a value without the knowlege of the encapsulating
class.

--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Hey Bob, I tried to check out your site that you have in your signature but
its down. Is it down or do you have a bad link in your signature?

Thanks,

glenn
 
One of the most long-lived dogma in the OO-purists camp is to never expose
fields as public.

However, I think there can be benefits in having public fields.

Consider a class Person with a public int property of Age and a public
string field called Name.

What the class Person tells you is that the Age property is somewhat
managed, perhaps the property validates that an age isn't a negative number
and so forth. The property protects you in some manner.

But the class also tells you that the Name field is not handled at all. The
Person class won't mind if you serialize an mp3-file to a hexstring and use
that as a name, hence it is your responsebility to check that input is
meaningful.

By going by the idiom of sporting all fields private and have public getters
and setters for all those fields, is extra work and bloats your code. But
what I think is worse is having Name as a property, which implies that it
validates input, while in fact it doesn't.

However, in some situations, like building user controls in asp.net; you
must sport all your fields as properties.

Hope this helps
- Michael S
 
Actually I fail to see your point. There seem to be a couple things you
might be forgetting.

1) Its impossible to know today what might come up next week or even next
year that causes a design to change. Starting out with public fields allows
decendents of a class to directly access those fields, even if later you
decide that exposing the customer name field was a huge mistake. Having it
use properties up front might take a little extra work on your part, but
your class is much more adaptable to future needs.

2) Your argument that exposing a field allows your class to be much more
powerful seems rediculous. What it seems you are actually doing is making
your class much less capable of changing with future needs that may arrise
because trying to go back and change a public field to a private field might
be an impossible task 2 years later.

If you choose to have public fields in your class designs then that is your
business and perhaps it works for you, however, telling someone that doesn't
understand the ramifications of doing that, that you "Should" do it, seems a
little rediculous. I think that exposing fields like that should be given
extreme care and in the end, I just don't see the advantage. You saved
yourself a very few keystrokes up front, but what have you potentially done
to yourself and those using your components later on?

Sorry if my wording sounds like I'm attacking you as I'm not. Just
expressing my opinion...

just my 2 cents,

glenn
 
Michael S said:
One of the most long-lived dogma in the OO-purists camp is to never expose
fields as public.

However, I think there can be benefits in having public fields.

Consider a class Person with a public int property of Age and a public
string field called Name.

What the class Person tells you is that the Age property is somewhat
managed, perhaps the property validates that an age isn't a negative number
and so forth. The property protects you in some manner.

But the class also tells you that the Name field is not handled at all. The
Person class won't mind if you serialize an mp3-file to a hexstring and use
that as a name, hence it is your responsebility to check that input is
meaningful.

By going by the idiom of sporting all fields private and have public getters
and setters for all those fields, is extra work and bloats your code. But
what I think is worse is having Name as a property, which implies that it
validates input, while in fact it doesn't.

I don't think it's particularly implying that - you're just inferring
it incorrectly. I think it implies more that the author of the code
cares about OO purity and the *potential* for validation in a future
release (while maintaining backward compatibility of both source and
binary).
 
glenn,

While I agree with you, and I never use public fields myself, do recall
that your advice applies only for programmers who are releasing DLLs to
the public, and so are bound by the contract that they create at the
outset.

If you release DLLs outside your organization (or work group), it _is_
difficult to change a public field to a public property, because it
requires that all client code be recompiled.

However, if you are doing in-house development and all code is under
control of your IS department, then it is _dead easy_ to change a
public field into a property later if the design requires it. All you
have to do is recompile all client code, which is a minor annoyance at
worst.

I'm not advocating using public fields... I don't, as a matter of O-O
purity, as Jon Skeet pointed out.. I just wanted to point out that for
some of us it's not as bad as you make it out to be. It really depends
upon what kind of development you're doing and who is going to be
calling your DLLs.
 
glenn,

While I agree with you, and I never use public fields myself, do recall
that your advice applies only for programmers who are releasing DLLs to
the public, and so are bound by the contract that they create at the
outset.

If you release DLLs outside your organization (or work group), it _is_
difficult to change a public field to a public property, because it
requires that all client code be recompiled.

However, if you are doing in-house development and all code is under
control of your IS department, then it is _dead easy_ to change a
public field into a property later if the design requires it. All you
have to do is recompile all client code, which is a minor annoyance at
worst.

I'm not advocating using public fields... I don't, as a matter of O-O
purity, as Jon Skeet pointed out.. I just wanted to point out that for
some of us it's not as bad as you make it out to be. It really depends
upon what kind of development you're doing and who is going to be
calling your DLLs.
 
Bruce, while I can see your point, its still incorrect for the following
reason:

Lets say I write a class and have a field in it that is public. I deploy
that class to only myself as in your example its not a big deal if I do
that.

I use this class for 2 years all the while writing directly to this field as
its my only method of doing so. My boss comes to me today and he informs
me that we have a serious problem. That fields contents are being written
to based on user input, and the users are seriously screwing up the data in
the field. We need to do some verification on the field before we write the
data into the class.

So, I now know more than I knew then, and I know that to do this, I need to
prevent anyone from writing to that field (Me in this case) and start
validating the input through a property. So I go and change the type to
private and provide the necessary property to Get and Set the fields value
along with my appropriate validation code and recompile all my apps that
used that class as this is not a big deal, right?

Wrong! The problem now is that I've since used that class a grand total of
122 times throughout 10 different modules, all writing to a field that is
now private and therefore doesn't exist. So now I have to go throughout all
this source code and update it before I can recompile and redistribute all
the necessary peices.

So, we can talk proper OO standards and processes, or we can just talk
facts. Having public fields in my opinion is just not very smart in the
long run. It may get the job done quickly today but what is to say it will
still work tomorrow. And when it does require another process what will it
take to fix it?

For me, I'd much rather have a series of get and sets for each field that
never get used than to take a chance of having a major headache one day when
someone asks me to do something I hadn't planned on.

Just my 2cents,

glenn
 
glenn said:
Actually I fail to see your point. There seem to be a couple things you
might be forgetting.

From what I have read below, I can see that you failed to see my point. But
I'll try to explain it to you.
As a systems architect, I am responsible for making sure that each project
I'm involved in; have a certain amount of quality; they vary in scale and
can easily be translated into how much our customers are willing to pay.

'Quality' for me, is a jagged array. There is performance issues, milestone
issues, deadline issues, readability and maintainability, and also a lot of
coffee involved. But in the end; - Quality == Economics.
1) Its impossible to know today what might come up next week or even next
year that causes a design to change. Starting out with public fields
allows
decendents of a class to directly access those fields, even if later you
decide that exposing the customer name field was a huge mistake. Having
it
use properties up front might take a little extra work on your part, but
your class is much more adaptable to future needs.

RUP might think so, while Agile-spawned methologies having the
YAGNI-principle. - You Ain't Gonna Need It!

How often do entities change? Do we code in Notepad or Visual Studio? How
much time does it take to refactor a sequence of objects? I know that ctrl-h
enables me to search and replace. VS2005 and especially Eclipse have
excellent support for turning a field into a property (get./set-method), and
a property into a method.

This is the real problem with the oldschool OO-purist camp. They still live
in a world of Notepad (edlin?) and Emacs. .NET is built on namespaces and
typed classes, not files and variant functions. Refactoring is a simple task
nowadays. Many principles in OO are just dogma.
2) Your argument that exposing a field allows your class to be much more
powerful seems rediculous. What it seems you are actually doing is making
your class much less capable of changing with future needs that may arrise
because trying to go back and change a public field to a private field
might
be an impossible task 2 years later.

Rediculous?

This is the classic Java-argument. They don't need Properties and Events
(while still having them in .jsp/struts in an awkward way *s*).

The Java argument: - Sure we don't need properties, we can settle for
getters and setters. We don't need events, we can have nested classes and
interfaces.

The great thing with (Anders Hjelsberg and...) the MPE-model, Methods,
Properties and Events, is that the destinction tells you something.

And I've heard the argument before. - But what if a property does work? But
if the method just return a value?

- Well, then you are a lousy coder and don't belong in my crew. The argument
is just not there. What if a programmer write the boolean method IsValid
that deletes all files with .mp3 as an extention on all your drives? That
dude is evil, incompetent and/or have a serious communication problems.

It's all about granularity. If you know how to use MPE and fields you know
what to expect. If you do it wrong you just have poor communication skills
as a coder.
If you choose to have public fields in your class designs then that is
your
business and perhaps it works for you, however, telling someone that
doesn't
understand the ramifications of doing that, that you "Should" do it, seems
a
little rediculous. I think that exposing fields like that should be given
extreme care and in the end, I just don't see the advantage. You saved
yourself a very few keystrokes up front, but what have you potentially
done
to yourself and those using your components later on?

Oh, I see your problem. The ctrl-shift-h and a find/replace takes seconds. A
ctrl-shift-b to rebuild also takes seconds. And by your reasoning; I should
have my coders do hours of coding and pageup/pagedown for the fear of
change?

Change is natural. There is nothing to fear. This is our job...

I do code in languages that sports properties. One of them is C#. Another is
Delphi. For obvious reasons netiher can handle a property as ref (var). And
that may be one argument why public fields are bad. If you sport a field and
it turns into a property it will no longer work with out and ref in C# and
therefor break code.

But there is a simple solution to that problem: - Treat fields as
properties.
As properties may or may not do work and may or may not do validation, we
already have the idiom of always making sure to pull the value from a
property once, use it locally, and set it after your done with it. The grand
old snapshot/transaction dilemma.

- Treat fields as properties.

Tada! Problem solved...
Sorry if my wording sounds like I'm attacking you as I'm not. Just
expressing my opinion...

This is an interesting topic. Our opinions may vary, the arguments may be
flamable; but I do respect you while I attack you!

My argument is still:

If a class (Person) denotes a concept of description (Name) while the class
has no concept of what Name might contain, it is far better to keep it as a
public field than turning into a property that does nothing.

A Method implies Work.
A Property implies Knowledge
An Event implies Action.
A field is just a variable (with type).

I live by the above implicit rules.

And back to Economics. If you worked for me and spent (invoicing)-time on
making a field into a property that does nothing, you would get some serious
spanking an also have to de-bloat your code on you spare time. Your code
would simple not pass my eye-balling test...
just my 2 cents,

I see your 2 cents and raise you 5. And I will raise you on the flop, street
and river. I've got two aces.. =)

- Michael S
 
Bruce Wood said:
glenn,

While I agree with you, and I never use public fields myself, do recall
that your advice applies only for programmers who are releasing DLLs to
the public, and so are bound by the contract that they create at the
outset.

If you release DLLs outside your organization (or work group), it _is_
difficult to change a public field to a public property, because it
requires that all client code be recompiled.

However, if you are doing in-house development and all code is under
control of your IS department, then it is _dead easy_ to change a
public field into a property later if the design requires it. All you
have to do is recompile all client code, which is a minor annoyance at
worst.

I'm not advocating using public fields... I don't, as a matter of O-O
purity, as Jon Skeet pointed out.. I just wanted to point out that for
some of us it's not as bad as you make it out to be. It really depends
upon what kind of development you're doing and who is going to be
calling your DLLs.

Bruce!

Thanks for coming to the rescue! Even if you don't agree with me totally.
But I just like your mindset and are hoping that you will comment on my
reply to glenn.

- Michael S
 
I don't think it's particularly implying that - you're just inferring
it incorrectly. I think it implies more that the author of the code
cares about OO purity and the *potential* for validation in a future
release (while maintaining backward compatibility of both source and
binary).

Inferring and Implying and perhaps Lying is just labels for the same
concept.
What I am trying to say is that granularity matters. See my reply to glenn.

There should be no confusion. The field Name and the property Age. What do
they communicate?

I think (and do expect) that anyone calling themself a 'coder', 'dev' or a
'programmer' have no problem with this.

The public getter for a private field is just old dogma. And of no use...

I vote for granularity!

With my sincere respect
- Michael S
 
glenn said:
Wrong! The problem now is that I've since used that class a grand total
of
122 times throughout 10 different modules, all writing to a field that is
now private and therefore doesn't exist. So now I have to go throughout
all
this source code and update it before I can recompile and redistribute all
the necessary peices.

****** Try this ******
------OLD CODE-----
public int X;

------NEW CODE-----
private int _x;
public int X{get{..};set{...}};

******************
Nothing breaks in this case (since everything is recompiled)


*********************************************
Personally, I would like C# to support IMPLICIT properties
Where any public fields are automatically converted to public properties
with private data storage.

for example:

public int X = 43; /// IMPLICIT property since it is a public field

is converted into private storage and a public property
///
private int _x = 43; /// _x would actually be a compiler generated
unique name;
public double X { get { return _x; } set { _x = value; } }

All public fields would actually be public properties
And these automatic properties would most likely get inlined.

If later you need a fleshed out property, you add it explicitly and it's
associated storage.

I love properties, but I hate typing in default properties

Bill
 
Michael S said:
Inferring and Implying and perhaps Lying is just labels for the same
concept.

They're not - inferring and implying are done by different parties.
(Lying is entirely separate.)
What I am trying to say is that granularity matters. See my reply to glenn.

There should be no confusion. The field Name and the property Age. What do
they communicate?

According to you, they communicate different levels of validation. To
me, the field Name indicates a lack of OO purity and nothing more.
I think (and do expect) that anyone calling themself a 'coder', 'dev' or a
'programmer' have no problem with this.

The public getter for a private field is just old dogma. And of no use...

Except for compatibility and different semantics in terms of pass-by-
reference etc...
 
Jon Skeet said:
They're not - inferring and implying are done by different parties.
(Lying is entirely separate.)

Darn, You got me! =)
According to you, they communicate different levels of validation. To
me, the field Name indicates a lack of OO purity and nothing more.

Yep, it's subjective. And we love you for your skills in OO Jon.
You and my dear Joanna Carter (who, by the way, have done an excellent job
on writing about patterns) should team up. =)
Except for compatibility and different semantics in terms of pass-by-
reference etc...

Well, as Bruce somewhat mentioned in another branch in this tree; - What you
export as a public assembly for use by others should know what it publishes.
Hence, properties.

Now please tell me what value there is of spending time on turning a public
field into a property that does nothing. All I see is time spent and
mis-communication.

- Michael S

(Still got my two aces, I think...)
 
glenn said:
So, we can talk proper OO standards and processes, or we can just talk
facts. Having public fields in my opinion is just not very smart in the
long run. It may get the job done quickly today but what is to say it
will
still work tomorrow. And when it does require another process what will
it
take to fix it?

Are we talking proper OO? What is that? I call it OO dogma.

And what is 'in the long run'? Have you actually maintained a solution
that's been running for like 2 years? 5 years? 15 years? With no
documentation at all?

If not, I can assure you, that the complications of field/properties is of
no concern for a maintainer. There are far more important concerns. Like
what the darn system do. It's all about readablility and granularity.

This is way too much textbook and dogma for me.
So I'll turn the table on you glenn;
- Please explain why I should have my coders spend time (money) to do
public getters and setters for a field, that in the end; is just a field.

Truly yours (for a spanking)
- Michael S
 
For me, I'd much rather have a series of get and sets for each field
that never get used than to take a chance of having a major headache
one day when someone asks me to do something I hadn't planned on.

For the record, so would I.
Wrong! The problem now is that I've since used that class a grand total of
122 times throughout 10 different modules, all writing to a field that is
now private and therefore doesn't exist. So now I have to go throughout all
this source code and update it before I can recompile and redistribute all
the necessary peices.

With all due respect, as you said: Wrong!

All you have to do is change the name of the (now private) field,
change all references to it within its owning class accordingly, and
name the new property the same as the field was named before. Presto.
You're done.*

Again, I'm not advocating the practice. Just pointing out that it's not
such a big deal in certain work environments.

I never make fields public, or even protected. My fields are always
private. Here's my reasoning for doing this. Programmers, when reading
code, tend to read with assumptions in mind. The more assumptions a
programmer can make about a piece of code, the easier it is to read,
because he/she has to keep less mental structure. For example, (and
this is the good bit) if I can _always_ assume that all fields are
manipulated _only_ within the owning class, then it's easier to
maintain the code. I can relax and think, "I don't have to worry about
this field being changed by any outside software." I can look over that
one class and find _all places_ where that field is changed, and modify
the code accordingly.

If I allow public (or protected) fields, then I have to remember
(constantly) that other classes could (unexpectedly) modify this
field... "behind my back" as it were... and I have to program carefully
to account for that. Yuck. It breaks encapsulation and makes code
difficult to maintain. Sometimes trivially so, sometimes awfully so.
However, I'm a lazy programmer and I don't like cluttering my brain
with unnecessary detail.

Yes, it's more work typing those extra properties, but then it makes it
easier on me later... and I end up reading code 100 times more often
than I write it. :)

* There is one exception that I think does point out why one should
always use properties rather than public fields. You can do this with a
property:

MyMethod(6, null, ref myObject.MyField);

Change "MyField" to a property and kaboom! You can't pass properties by
reference or as "out" parameters.

However, that's the only case in which you would have to modify client
code. For my part, that's just another good reason to always use
properties.
 
Back
Top