Search This Blog

Monday, August 30, 2010

what is the difference between property and variable

what is the difference between property and variable, why can't we
just use variable in a class implementation.
Actually my question is variable and methods are enough. Property seems to
be reductant ?

First of all, you should never expose a member variable directly. Always
make it private which is a standard OOP principle. Otherwise you weaken
encapsulation by exposing your object's implementation to the outside world.
Imagine if you decide to change how your object works later on for instance,
say, by changing your variable to some other incompatible type. You would
then break all existing clients of your object which would need to be fixed
in order to accomodate your change. A "get" and/or "set" function wrapping
your variable is the usually remedy for this (allowing you to change things
without breaking clients). However, a property is a high-level, built-in
construct designed explicitly for this purpose. It's much cleaner than using
a "get" and/or "set" function IOW. Not only does it instantly convey its
intended purpose to other readers (improving your code's legibility), but
it's also specifically recognized by different tools, controls, etc. For
instance, you can pass an object to the native "PropertyGrid" control and it
will automatically populate the control with all properties in your object.
It can only do this however because it's able to identify a "property"
unlike an arbitrary "get" and/or "set" function. This is how the Windows
forms designer works in Visual Studio for instance. Note BTW that a property
need not deal with member variables at all. It can do anything it wants,
calculating your property on-the-fly if you wish (though it's normally
better to avoid this unless the calculation is extremely simple).
Properties are more maintainable than fields. Some properties do not have the equivalent field - you need to write some code to set/get them.

Simple example: say you have a car object. It has a mileage and a gallons as fields. You can make a property MPG by dividing these fields. Notice that there is no MPG field inside an object - you do it on the fly by using a property. And that property is read-only - you cannot set it. It can only be changed by changing mileage field or gallons field.

From the other hand - the critical code path (large loops, for example) should avoid using a lot of properties or get the properties once before the loop.

No comments:

Post a Comment