About Me

Hyderabad, Andhra Pradesh, India

Tuesday, January 3, 2012

Why are the get/set properties so useful?

Lots of reasons, but the biggest one is control and conversion.

Control:
Let's assume that for some reason, my value can only be from 1-10.
If I allow the user to assign a value outside that range, my program
may
crash or do weird things. If the setter does not allow a value outside
the
range 1-10, I don't have this problem. Likewise, let's say that I want
to
change some OTHER variable when you set one of the values. I can do
that in the setter. Finally, suppose that I don't want to do things if
the
value you give me is the same as the current value. I can do that in a
setter.

Conversion:
If I have a set routine that takes a value of another type, such as a
string
instead of an integer, I can convert it to whatever I want without the
user
being aware of what my internal representation is.