Prev: tv
Next: too much OOP ?
From: Veloz on
Hi there

What's the current consensus regarding how you should code the methods
in a class with repsect to the class's fields?

That is, in class X, if you have private field named privateA, but
also have a public property to wrap it up, named publicA, should
methods in class X be accessing privateA or publicA?

I have the sense that some people are suggesting that class code
should access its own fields via publicA.

Michael
From: alAzif on

> That is, in class X, if you have private field named privateA, but
> also have a public property to wrap it up, named publicA, should
> methods in class X be accessing privateA or publicA?
>

My understanding is that properties are simply a language commodity
for accessing private fields; thus, I'm constantly cautious about what
properties I make public, and the reasons why I do so. I don't want
people to be strongly coupled to a piece of data, because I want the
flexibility to change the inner workings of the class as I see fit.

Presumably, a method sees the private fields and is perfectly capable
of depending on them, as it would be the first to resent the impact of
any change at that level; ideally, it is also the only one affected by
such a change.

I wouldn't recommend doing so, but this is closer to being a matter of
style.

Jehu
From: Daniel T. on
Veloz <michaelveloz(a)gmail.com> wrote:

> What's the current consensus regarding how you should code the methods
> in a class with repsect to the class's fields?
>
> That is, in class X, if you have private field named privateA, but
> also have a public property to wrap it up, named publicA, should
> methods in class X be accessing privateA or publicA?
>
> I have the sense that some people are suggesting that class code
> should access its own fields via publicA.

When exiting a public method, the invariant must hold true, that isn't
necessarily the case when you are in the middle of a method (whether
public or private.) If a method in X needs to modify the value of
privateA, but isn't prepared to ensure the invariant immediately after
that modification, then it must access privateA directly rather than
using the publicA method.
 | 
Pages: 1
Prev: tv
Next: too much OOP ?