views:

35

answers:

2

Hello everybody

I know that each class should to do its own job. So i always try process my fields by only in class's methods.If another class processing on my public fields i feel that there is something wrong but is it always right thing to make define private fields ? Would be bad design or code If i let other classes to change my public fields ?

By the way is there name about this design or term word ?

A: 

Yes, it's considered bad design leaving fields public. Keep your fields private, and make use of public properties instead.

class Graph
{
    /// <summary>
    /// A field of the Graph by list of points
    /// </summary>
    private List<Point> lineGraph = new List<Point>();

    /// <summary>
    /// A Property to get and set the Graph
    /// </summary>
    public List<Point> LineGraph
    {
        get { return this.lineGraph; }
        set { this.lineGraph = value; }
    }
}
BennySkogberg
but consider that there is no any advantage to use property in some situation. And this is one of them.
Freshblood
Freshblood: You are correct. You just have to be aware of the consequences - mostly that you forfeit any control over the setting of these values (no boundary checks or other checks besides type correctness). And if you discover later that you need a check, you do not have a defined entry point and need to change every occurrence of this value being set. This is perfectly legit in simple classes like "Point", or probably even in Benny's example.
relet
It's true that this example doesn't make use of the benefits of a property. But it is possible to add conditions to the set{} if we wish to do so. Every programming book I've read facilitates this technique, and I'm convinced this is the appropriate method in every programming language. BR -
BennySkogberg
+2  A: 

This is called friend classes.

It is not always a bad design principle, but you really have to ask yourself why you would like to expose a field directly and not through a method. If you have a good reason, then you can expose the field directly. However, in most cases such reason does not exist

Henri
+1 I often find useful to have public fields in my simple mocking classes, so that the test classes can manipulate it with ease.
Jordão