Re: OOP question about properties & methods

Tech-Archive recommends: Fix windows errors by optimizing your registry



Bruce One <raul@xxxxxxxxxxxxxxxxxxxxxx> wrote:

Kelly,

My name is Barry!

Could your explain better points 3 and 4?

3) If reading doesn't modify the observable state of the class

Just reading a property shouldn't change the property. For example:

Button b = new Button();
// ...
string text = b.Text;

This action (reading b.Text, which is a property) shouldn't change the
property. Another example:

IEnumerator x = new List().GetEnumerator();
bool b = x.MoveNext();

This action, MoveNext(), changes the enumerator - it moves it forward
one. Therefore it shouldn't be a property, it should be a method (which
it is).

4) If writeable, then writing and subsequently reading gives the same
value (i.e. { a.Prop = 42; Debug.Assert(a.Prop == 42); }), unless
writing the property throws an exception because of a problem with the
value.

When there is a property, people expect this:

b.Name = "foo";
if (b.Name != "foo")
throw new Exception("Something went wrong!");

If this code would throw an exception for your property, then it
shouldn't be a property - it should be a method.

This only matters if the property is writeable - that is, it has a 'set'
method.

-- Barry

--
http://barrkel.blogspot.com/
.


Quantcast