I have a property in my class that has a lot of logic in set accessor:
private String text;
public String Text
{
get { return text; }
private set
{
// some actions with a value
value = value.Replace('a', 'b');
text = value;
}
}
How can I prevent other developers (or even me) from changing field instead of property inside of this class ?
If somebody writes something like this:
public Test(String text)
{
this.text = text;
}
it will break the logic of my class !
Fields are normal variable members of a class. Generally, you should declare your fields as private, then use Properties to get and set their values. By this way you won't affect their values them directly.
Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. For example, if you need to add extra validation, or to change a stored field into a calculated you can do so easily if you initially exposed the field as a property.
Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.
There is a correct way to do this. Consider the old adage "All problems in computer science can be solved by another level of indirection".
What you do is create a class that knows how to set the value of the text field properly.
class TextSetter
{
private string text;
public TextSetter(string text)
{
Text = text;
}
public string Text
{
get{ return text;}
set{ text = value.Replace('a', 'b');}
}
}
Then in your first class instead of
private string text;
you have private TextSetter text
; now there is never any chance that someone will accidentally set the value directly.
you could even generalise this, if it's a common problem
class FieldSetter<T>
{
private T field;
private Func<T, T> setter;
public FieldSetter(Func<T, T> setter, T field)
{
this.setter = setter
Value = field;
}
public T Value
{
get{ return field;}
set{ field = setter(value);}
}
}
Feel free to rename as you see fit.
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