Possible Duplicate:
Why use getters and setters?
Why use getters and setters?
The getter and setter method gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement.
Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will. Typical example, consider having a dateOfBirth parameter.
1) getter and setter method gives you centralized control on how a the particular field is initialized and provided to the client which makes the validation and debugging much easier. you can simply put breakpoints or print statement to see which thread are accessing and what values are going out.
The main difference between making a field public vs. exposing it through getters/setters is holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly.
To limit access to an internal state of an object.
Consider the classic example of a class of geometric shapes. Say, a Circle object. When you set the radius, you may want to automatically calculate the area (which would be a read-only property)
class Circle
{
float radius;
public float Radius
{
get { return radius; }
set { radius = value; area = Math.Pi * radius * radius;}
}
float area;
float Area
{
get { return area;}
}
}
If you allowed direct access to the "radius" data member, you could not update area
when it changed. Further, if you allowed direct access to area
, users could change it willy-nilly without regard for radius
.
To encapsulate, and that way you make how you store data within your class an implementation detail. If your class has a getter/setter:
private string _mystring = string.Empty;
public string SomeValue
{
get
{
return _mystring;
}
}
That allows you to change how you manage "SomeValue" in the future. For example, you may decide that rather than storing it in a string, it's actually going to be a Guid under the hood. Now you could go for:
private Guid _myguid= Guid.NewGuid();
public string SomeValue
{
get
{
return _myguid.ToString();
}
}
Anywhere that your class is used and the "SomeValue" property is accessed will remain unbroken this way.
Validation
You can also validate the value passed in as well, so in another example:
private string _mystring = "My Value";
public string SomeValue
{
get
{
return _mystring;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new InvalidArgumentException();
}
else
{
_myString = value;
}
}
}
To ensure that the stored string is never set to a null/empty string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With