what is the different of the member variable and property?

T

Tom Shelton

In my experience, any thing that may have prompted the change of a field to
a property also broke the clients in ways that initially exposing the field
as a property would not have protected against.

By far the most common circumstace is a change in validation rules. If the
item is not already being validated, then having it as a property instead of
a field does not usually save the need to make changes at the client. If
the validation is actually being handled in a way that the client does not
need to know about, then it makes no difference whether it is a field or a
property. If the client does need to know about it, then the client needs
to be changed anyway.

In other words, the programming standard of always using a property instead
of a field only makes sense if there are matching standards that apply to
the use of that property - ie always providing a validationfailed routine.

In practice, any time the use of a field changed in this way I have added a
property and deprecated the field.

In my own code I prefer to always work through properties. I can't justify
imposing that as a standard, however.

Your logic makes little sense to me. If you change a field to a property,
then that is a breaking change to clients - period. If you change a properties
implementation, that is not a breaking change - as long as you stay with in
the contract of the object. In other words, if your contract used to be you
only returned integers between 1 and 10, and you suddenly start returning 0 or
11 then yes - you've broken the clients, but on a logical level not binary.

To be honest, I'm really confused by the resistance to idea that a field
should never be public. Encapsulation is one of the basic pillars of OOP...
Languages that lack properties, such as Java, have a whole naming patterns
around this idea.
 
J

James Hahn

Tom Shelton said:
Your logic makes little sense to me. If you change a field to a property,
then that is a breaking change to clients - period.

I wasn't referring to a change from a field to a property - I was referring
to changes in interface design that I have experienced that might have
required a field (had it been implemented as such) to be changed to a
property, and I commented that it was unusual that such a design change did
not also break the clients. Simply, the claim that avoiding a field in
favour of a property means that future design changes (such as applying
validation) can be implemented without breaking the clients just doesn't
hold water in real life - in most cases the clients are already broken by
the design change.
If you change a properties
implementation, that is not a breaking change - as long as you stay with
in
the contract of the object. In other words, if your contract used to be
you
only returned integers between 1 and 10, and you suddenly start returning
0 or
11 then yes - you've broken the clients, but on a logical level not
binary.

My point was that if the change in implementation does _not_ break the
client then it is irrelevant whether the item was an exposed field or a
property. And if it _does_ break the client then it is the design change,
not the choice to use a field, that caused the break. Choosing a property
over a public field has not avoided the need to work on the client, as
claimed.
To be honest, I'm really confused by the resistance to idea that a field
should never be public. Encapsulation is one of the basic pillars of
OOP...

Encapsulation is not an absolute. Properties provide a managed form of
access to encapsulated variables. Public fields are less managed. Private
fields are fully encapsulated. Use what is appropriate in the
circumstances.
Languages that lack properties, such as Java, have a whole naming patterns
around this idea.

There may be other reasons for not exposing fields, but the lack of
properties in Java is not one of them. It certainly demonstrates many of
the advantages in using properties, but that's not the same as proposing
that fields should never be public.
 
T

Tom Shelton

I wasn't referring to a change from a field to a property - I was referring
to changes in interface design that I have experienced that might have
required a field (had it been implemented as such) to be changed to a
property, and I commented that it was unusual that such a design change did
not also break the clients.

If you simply make all access through properties then the situation you are
refering to - requiring a field to be changed to a property - should NEVER
happen. Since there are no fields in the first place.

Simply, the claim that avoiding a field in
favour of a property means that future design changes (such as applying
validation) can be implemented without breaking the clients just doesn't
hold water in real life - in most cases the clients are already broken by
the design change.


My point was that if the change in implementation does _not_ break the
client then it is irrelevant whether the item was an exposed field or a
property. And if it _does_ break the client then it is the design change,
not the choice to use a field, that caused the break. Choosing a property
over a public field has not avoided the need to work on the client, as
claimed.

Again, that is wrong. If an implementation change requires a field to become
a property, then the clients are broken. Period. This is a binary change at
the IL level, a simple access vs a method call.

If you encapsulate the fields as properties, then a change of implementation
may break existing clients, but isn't guarenteed. In fact, if the the logic
is likely to break existing clients then the usual practice is to create a
new interface or property.
Encapsulation is not an absolute. Properties provide a managed form of
access to encapsulated variables. Public fields are less managed. Private
fields are fully encapsulated. Use what is appropriate in the
circumstances.

I have not in the last 10 years ever seen the need of a public field - beyond
a constant value. In fact, I NEVER declare fields as protected, protected
internal, or internal. Fields are private - period.

Access to those fields are controled via properties of the necessary scope. I
followed this practice even in my VB classic code - and it's served me well.
There may be other reasons for not exposing fields, but the lack of
properties in Java is not one of them.

The lack of properties has nothing to do with fields being public, I agree.
The point of the comment was that the reasons for NOT exposing fields is so
universially recognized that a pattern has emerged in that language to
compensate - it is a convention. Properties just formalize this pattern in a
more convenient and transparent syntax.
It certainly demonstrates many of
the advantages in using properties, but that's not the same as proposing
that fields should never be public.

They simply NEVER should be public. To me this is an absolute.
 
H

Herfried K. Wagner [MVP]

Tom Shelton said:
The major point being made is that exposing a member variable directly to
outside of the containing class is a bad idea. For example, what happens
to
all existing client code if suddenly you need to add validation to a
member
field? Or you want to implement change notification? Or you realize that
the
member field really should be a calculated value? I'll tell you what
happens
- all the code accessing the value - even if you don't change the name
breaks.
If you had just used a property in the first place, then client code
would
be blisfully ignorant of the change....

Encapsulation is a good thing, because it insulates client code from
changes
in implementation.

I agree with that, which means that I would not expose fields directly.

However, adding validation code would often constitute a break of the
originally defined semantic contract. So in this case it would not matter
if existing code broke.
 
A

Armin Zingler

I want to look at code and see it makes sense at the moment I look at it. If
I compare the one-line public field version to the multiline property
version, I choose the former. It's multiple times shorter and provides
everything I need.

If I see such a get/set-only property I'd ask the author if he's planning to
add additional code. If he said "no", I wouldn't understand it.


Anyway, we are free to choose whatever we like. :)


Armin
 
T

Tom Shelton

I agree with that, which means that I would not expose fields directly.

However, adding validation code would often constitute a break of the
originally defined semantic contract. So in this case it would not matter
if existing code broke.

True, validation code would tend to do that. That would be a reason to create
new properties or a never version of the class, and deprecate the old one.
That way, existing clients are not broken, but get warned next time the
compile that they are using out of date objects :)
 
J

J.B. Moreno

Michel Posseth said:
So from my perspective public class variabels are a big red dot in
code analysis ,a absolute no go area i just can`t understand why a
coder would criple his app on forehand , as i can do with properties
what he can`t but he can`t do what i can with properties and after a
release to the outside world he has really a problem if he sees the
light .

THree words: By Ref Parameter.
 
M

Michel Posseth [MCP]

Armin

I want to look at code and see it makes sense at the moment I look at it.
If
I compare the one-line public field version to the multiline property
version, I choose the former.

if you declare every member variabel as

Private _Name as string

You can refactor this with every code tool that conforms with MSF to a
property with only a right mouseclick and choosing the refactor to property
option
or by just choosing the apropriate keyboard shortcut .
It's multiple times shorter and provides everything I need.

It provides everything you need at that moment , however you forget that you
limit future revissions of your app
If I see such a get/set-only property I'd ask the author if he's planning to
add additional code. If he said "no", I wouldn't understand it.

My answer as the author of such a product would be , "I have no idea what
the future will bring , but bether be prepared for for the future as
limiting myself on forehand "
Anyway, we are free to choose whatever we like. :)

Wel it depends... if you are a sole developer on private products you are ,
however if you are a a buisness developer who writes libraries that are
commonly used in your organization or a developer who writes products that
are used by third party`s IMHO you are not .

In the company where i was previously employed ( automotive cataloging ) we
wrote catalogs that were integrated with financial systems , ordering
systems etc etc
if we would break our interface we would have a serious problem and facing
claims of our customers our customers were mostly from German speaking
countries so the term "Pflichtenheft" does probably ring a bell on your
side ?
Anyway, we are free to choose whatever we like. :)

It is just what is your definition of freedom , ( free to do the non obvious
thing to do ? )

regards

Michel Posseth
 
J

J.B. Moreno

James Hahn said:
My point was that if the change in implementation does _not_ break the
client then it is irrelevant whether the item was an exposed field or a
property. And if it _does_ break the client then it is the design change,
not the choice to use a field, that caused the break. Choosing a property
over a public field has not avoided the need to work on the client, as
claimed.

While it's true that it's the design change that broke the contract,
it's misleading to say that it wasn't the choice to use a field that
caused it to break.

If you started off with a field and then later discover that the best
implementation of what your class does can only be done with that field
being a property, then the decision to use a field put you in a
position of having a substandard, possibly broken, implementation, or
to break the contract. If you'd gone with a property in the first
place, you might have been able to keep the class contract and still
provide the better implementation.

Just about the only advantage a field has over a property is that the
field can be used as a by ref parameter. If that's likely, use a
field, if it's not then use a property.
 
A

Armin Zingler

Michel said:
My answer as the author of such a product would be , "I have no idea
what the future will bring , but bether be prepared for for the
future as limiting myself on forehand "

I do not take imaginary things into account that are not even planned.
That's a general attitude. If I made exceptions here and there, I wouldn't
know where to stop. This makes (my) life much easier because I just have to
focus on what has to be done (which already takes things planned for the
future into account) without burdening my thoughts with things that
might happen - or maybe not. I am not able to work that way. In the end
it's easier even if you have to make braking changes in the future, but
then I can learn from it and wonder if my planning has been done thoroughly
enough. Untill now, this attitude served me well.

Wel it depends...

No, it doesn't. _I_ am free because...
In the company where i was previously employed[...]

....I'm talking about VB, not about your company.

As I said in a previous post, in most cases I also use a property because
there's a reason to do so.


Armin
 
J

J.B. Moreno

Tom Shelton said:
Temporary Variable.

Not if it's more than a simple backing field. Also not if it's a
lambda or if it's down a couple of levels deep (sub with by ref calling
a sub with by ref).
 
M

Michel Posseth [MCP]

Wel it depends...

No, it doesn't. _I_ am free because...
In the company where i was previously employed[...]

...I'm talking about VB, not about your company.

As I said in a previous post, in most cases I also use a property because
there's a reason to do so.

Okay i understand you don`t want to conform to MSF and OOP or just are in
the lucky position that you now in forehand how your project
wil evolve in the future , i and most people who code to get the shelves
filled and the heater running are not in that luxury position .

If a class and the classes that use it are always compiled together, than
properties don't buy you any advantage. If they are compiled separately,
then using properties instead of fields looks like a better idea. writing
properties makes sense at the locations where your component interfaces with
other components.

However for the sake of following guidelines
http://msdn.microsoft.com/en-us/library/ta31s3bc(VS.71).aspx
wich wil give you so much more advantages i just use properties whenever i
need a public or friend field

Anyway, you are free to choose whatever you like there is no property police
watching over your shoulder and slapping you on the fingers if you don`t
follow these guidelines .

But in my version of VS i get the below warning if i just declare a public
field so i guess someone there in Redmond doesn`t want me to declare public
fields

CA1051 : Microsoft.Design : Because field 'Form1.bla' is visible outside of
its declaring type, change its accessibility to private and add a property,
with the same accessibility as the field has currently, to provide access to
it. C:\Studio\NeProS\Diversen\ADQuery\Test\Form1.vb 5 Test

so just for completeness i digged a bit deeper and found this interesting
posting in a simular thread

###############

Michael Fanning - MS
Development Lead for Visual Studio static code analysis
There are many good reasons to avoid externally visible fields. They cannot
be used to satisfy interface contracts. It is difficult to determine when
they are accessed in debugging scenarios. You cannot apply declarative
security to them. Etc. Converting a field to a property is a breaking
change. Therefore, the general guideline (which is quite firm) is that all
fields should be private and accessed through trivial property accessors
where possible (so that the code is inlined and very performant). One of the
summary arguments supporting this is that there are many pitfalls avoided by
doing so and no substantive negative outcomes by making the change.

In your case, do you truly need these items to be protected? You could make
them internal, for example. Or, you could use the new Whidbey mechanism
whereby a property's getter is public, and the setter is protected. The
backing field would be private.

Or, finally, if you never intend your assemblies to be reused by third-party
developers, you could simply disregard this rule. The guidelines in question
here have to do with potential problems that arise when an arbitrary set of
developers reuse your public API. If that isn't the case here and there's no
tangible vlaue from taking the change, you shouldn't feel req'd to make it.

###############

Regards



Michel Posseth







Armin Zingler said:
Michel said:
My answer as the author of such a product would be , "I have no idea
what the future will bring , but bether be prepared for for the
future as limiting myself on forehand "

I do not take imaginary things into account that are not even planned.
That's a general attitude. If I made exceptions here and there, I wouldn't
know where to stop. This makes (my) life much easier because I just have
to
focus on what has to be done (which already takes things planned for the
future into account) without burdening my thoughts with things that
might happen - or maybe not. I am not able to work that way. In the end
it's easier even if you have to make braking changes in the future, but
then I can learn from it and wonder if my planning has been done
thoroughly
enough. Untill now, this attitude served me well.

Wel it depends...

No, it doesn't. _I_ am free because...
In the company where i was previously employed[...]

...I'm talking about VB, not about your company.

As I said in a previous post, in most cases I also use a property because
there's a reason to do so.


Armin
 
J

James Hahn

You seem to be deliberately trying to misunderstand the point that I am
making.

I did not suggest that the choice of an exposed field instead of a property
was a good choice - in fact I stated that I will always choose a property.

The real point is that the examples provided to support the claim that
exposed fields should be banned do not hold water in practice.

Let me give an example I actually came across this week.

A payroll system allows entry of expense claims. The claim type is a
dropdown list, populated by a list of items provided by the class. One claim
type has now been declared invalid, so the first thought was that it should
simply be removed from the list provided (this possibility was considered in
the initial design). But the client uses the same list for enquiries on
past claims as for entry of new claims, so with the item removed the claim
type does not display correctly for some enquiries on old claims - a problem
overlooked in the initial design. Second thought is therefore to leave the
list as is and validate the claim type when it is returned, rejecting it if
it is the now-invalid type. The problem with this is that client has no
process for dealing with invalid claim types (why should it - it only
processes types as per the provided list?). So the choice came down to
rewriting the client or rejecting the claim under a generic 'invalid'
heading after the claim is submitted. This was the decision taken, and it
is now a significant proportion of support centre calls.

Validating the claim type was an easy change in the class: just a few lines
of code comparing the type against an external list (after splitting the
original list list into "current" and "all"). But - and this is the
important point - it would have made no difference whether this item was
updated in the class via a property or an exposed field. The validation
process in the class would have been exactly the same in each case.

This type of issue, in my experience, is typical of the sort of problem that
occurs with data validation. That's why I object to statements such as "For
example, what happens to all existing client code if suddenly you need to
add validation to a member field?" which purport to support the use of
properties over fields. I simply cannot see how the problem of suddenly
needing to add validation is made simpler by using a property rather than an
exposed field - the claim does not hold water. The problems involved in
adding validation invariably require changes to the client. When changes to
the client are required then _if_ the item has been set up as a field by all
means take the opportunity to change it to a property if that's your
programming style. But originally setting it up as a field has not affected
the work that needs to be done to solve the problem. If the design change
does not require changes to the client, then applying validation in the
class is unaffected by the method of accessing the item.

Similarly for change notification - if it didn't exist in the original
design then adding it is not going to affect the clients unless they are
also changed, and if they are both being changed then take the opportunity
to change the field to a property if you want. Or, do as I mentioned and add
a parallel property, deprecating the field: new code uses the property and
monitors for changes, old code simply uses the field. But whatever the
choice, the task of implementing change notification is same regardless of
how the item was originally set up - it is not an example of why properties
are better then exposed fields.

As for a member field that "really should be a calculated value", that's
either a validation process (see above) or requires some change in the
client. Again, whether the item was originally set up as a field or a
property makes no difference to the problem.

Perhaps there are good reasons for considering exposed fields a bad idea,
but the examples provided to date do not, for me, justify banning them.

Years ago MS produced a small booklet explaining what OOP was. I think it
was part of one of the C++ packages. It made fascinating reading - each
chapter had a few paragraphs describing a feature of OOP, followed by
several pages detailing the problems that feature created and how to get
around them. It should be required reading for any .NET programmer who is
trying to balance an enforced policy against recommended standards.
 
J

James Hahn

J.B. Moreno said:
If you started off with a field and then later discover that the best
implementation of what your class does can only be done with that field
being a property, then the decision to use a field put you in a
position of having a substandard, possibly broken, implementation, or
to break the contract.
While that is theoretically reasonable...
If you'd gone with a property in the first
place, you might have been able to keep the class contract and still
provide the better implementation.
....I cannot recall any circumstance where I was forced to change a field to
a property other than as a result of change in the class contract that was
forced on me for some other reason.

(You have used the term 'best implementation'. I am assuming that to mean
'one that works'. Otherwise the discussion is about standards (a discussion
which could go on forever) rather than an 'absolute' rule, which was how the
original comment was expressed.)

In other words, there may have been some poor design decisions made, but if
a field provided the required functionality for the original design, it was
that design, not the decision to use a field to implement it, that was
wrong. I have provided an example elsewhere of exactly that sort of
oversight in an original design. Forcing the programmer to use a property
instead of a field would not have fixed the design problem, and, based on
where I see this issue cropping up in old code, would not have made fixing
the design problem any easier.

That's why I do not accept that the examples provided demonstrate that a ban
on exposed fields is supportable.
 
M

Michel Posseth [MCP]

You are right ,,

It is a general guideline and not a absolute rule

"that all fields should be private and accessed through trivial property
accessors
where possible (so that the code is inlined and very performant). One of the
summary arguments supporting this is that there are many pitfalls avoided by
doing so and no substantive negative outcomes by making the change"

However when someone uses the term 'best implementation'. or 'Good / Best
coding practice' i guess that this person ( like me ) is talking about
the common and obvious way of doing things in current buisness coding ,
there are people outta there that believe that using GOTO in VB.Net 2008 is
perfectly valid with the argument "it just works" the term 'best
implementation'. or 'Good / Best coding practice' is mostly defined by
what is stated in the official guidelines , code analysis tools and the
most important common logic .

I was once a management trainee , and one of the key rules i have learned
then i enforce every day in my personal and private life
i believe the correct dutch to english translation is "before investment
perform a cost-benefit analysis"

so for this dicussion ask yourself the following questions
What does it cost me to create from every public field a public property ?
What is the expected benefit in contradiction of not doing it ?

Well i guess that the conclusion will be that your investment is minimal (
extra 2 mouseclicks, or keyboard stroke to action key to refactor tool )
but the estimated benefits are high in certain situations , but are zero in
the absolute other extreme .

Analogy ;
Past year i went on a holliday to South America so i went to a tropical
desees hospital ang got some shots worth of 150 euro`s
my brother in law who was also joining on the trip said , why did you do
that ? i never got annything there ( he was there before )
and indeed he and so did i never catched annything during that trip .

There is no law stating that you should get tropical desees shots if you
visit Colombia although the Dutch national health bureaus "recomends" to get
certain shots
it is not enforced , i just followed my conclusion in that one simple
management rule "before investment perform a cost-benefit analysis" my
brother in law translated this to, you just threw away 150 euro`s !

I guess this whle discussion is about people who get there tropical desees
shots and those who dare to take the risk of comming home with Yellow fever
or something else :)

Having said so it is time for me to step out of this thread as i believe
that investing anything more will not benefit me :)

regards

Michel Posseth
 
C

Cor Ligthert

Tom,

I don't know if the tale "The new clothes of the King" is as known in the
USA as in Europe, I hope so.

Therefore, all what is written in this thread on my question too you looks
to me as an answer to that tale.

I am sure that Armin like me could have given those answers as well.
However, (Armin I hope you don't mind I use your name to exclude you from the
others) we don't see where a public property with both get and set full
access is distinct from a public field (beside things as property grids etc.)
We both use properties and know most common theories and I always follow the
crowd after the King too with using for public access only properties).

I am however curious if there is a real solid answer then "Everybody sees
that the clothes of the King are beautiful" which I have read here many times.

Mostly used in this business as: it is "best practise" everybody should know
that.

Cor
 
J

J.B. Moreno

-snip-
That's why I do not accept that the examples provided demonstrate
that a ban on exposed fields is supportable.

A ban isn't supportable, in fact I gave an example elsewhere of one of
the minor drawbacks of properties that might cause you to use a field.

The answer is neither a ban on fields or simple/*automatic properties.
It's to consider the code and then choose which is most appropriate --
but if you don't see a difference (i.e. you don't think you'll need to
use it as a ref parameter and you don't think you'll want to make the
property more complex in the future) then choose to make it a property
as it gives you the greatest number of choices in the future.


*Automatic properties should have been done by adding a keyword to the
property declaration and a pseudo variable "backingValue", allowing the
hidden backing variable to used with all properties, and not just those
without an implementation. This would have facilitated code reuse and
refactoring. As well as encouraged all access to a property to be done
through the property and not through the backing variable.
 
J

James Hahn

FWIW, I just came across an example - the first of its kind that I can
recall.

A complex piece of engineering code consists of hundreds of lines of
formulae, each one independently checked and signed off, and uses about 16
properties as input to the calculation and generates about 6 property values
as results, of which two are error values (or 'confidence' indicators).

Each property has between several paragraphs and several pages of detailed
description, each of which is a quality-controlled document. This is a
serious bit of code.

But the programmer has exposed four fields as additional error indicators.
These are not used by most clients, but can help to indicate the source of a
low confidence score, such as mismatched or inconsistent input parameters.
Most clients provide pre-validated input values, but those that don't can
use these fields to help confirm that the parameters represent a valid set
of data, or to identify the cause of a problem.

The programmer has made a distinction between tightly defined and controlled
confidence values returned as properties, and 'internal' error values with a
much less precise definition, but which are nonetheless useful, by providing
the latter as fields.

Changing these values into properties would have required preparing QC
documentation for their calculation and meaning, something that was neither
necessary nor justifiable. I had to admit that the design decision was
correct, though more as a business decision than a question of good or bad
software design.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top