Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forbid the use of fields instead of properties? [duplicate]

Tags:

c#

properties

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 !

like image 638
eden_lane Avatar asked Apr 14 '14 06:04

eden_lane


People also ask

Should I use fields or properties?

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.

Why are properties better than fields?

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.

Why are properties used in C#?

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.


1 Answers

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.

like image 145
Binary Worrier Avatar answered Oct 12 '22 23:10

Binary Worrier