Possible Duplicate:
Why use getters and setters?
In C#(ASP.NET) we use getter and setter methods to set properties of private variables but same thing can be done if we declare that variable as public. Because at one end we are restricting user from accessing that variable by declaring it as private and on other end we are allowing user to access those properties by using getter and setter properties. I can't understand its significance.
by using getter and setter you hide the internal implementation of your class. which means in the set method of a setter, you can run a whole algorithm to parse the input data into your internal data structure. you'll be able to later change your implementation without any impact to your users.
now if you expose your internal members as public, you can't hide them anymore, and any change you make to your class internal definition will probably break the user usage.
In C#, the preferred method is to use Properties.
The advantage of this is that it exposes a convenient way of getting (or setting) data, but without exposing implemention details of the class.
A Property, or a getter or setter, can implement additional logic, for example:
- Calculating a value based on some private data (rather than just returning a value directly)
- Checking and validating data provided (to prevent overflows or out of range input).
By doing this you seperate the interface to your class from the implementation, allowing you easily to change the way your code works internally from how it is publicly accessed.
Because it allows you to override those properties in inherited classes, add validation / INotifyProperty changed handlers at a later date, and preserves binary compatibility between versions
精彩评论