4

So I know classes and structures are structures of data. Class fields are by default private and structure ones - public. Like public: / int a; for C++ and public int a; for C#

But other ways of access these fields are by making them private and use functions/methods. Like SetValue(int value){a = value;} and GetValue() { return a; } or I've even heard of the new cool {set; get;} in C#.

But why? Many people have told me 'other people could access your variables this way, so make them private'. I don't get it, what difference does it make making them public and just use them obj.a = 3; or making them private and doing obj.SetValue(3);? Could someone (even briefly) explain what the differences are and how can s.o. get to those fields when they're public?

11
  • 1
    For instance, you may only wish to expose a public getter, keeping the setter private. { get; private set; } in C#.
    – nphx
    Commented Nov 24, 2013 at 21:25
  • 3
    Categorical statements like "always make members private" is ... stupid. It's an excellent "guideline" ... and a lousy "rule".
    – paulsm4
    Commented Nov 24, 2013 at 21:26
  • 3
    saying {set; get;} is new makes me feel young again :)
    – sa_ddam213
    Commented Nov 24, 2013 at 21:28
  • 1
    stackoverflow.com/questions/1180860/… Commented Nov 24, 2013 at 21:36
  • 1
    @Joker_vD: You should encapsulate the complexity, not make the complex by make-every-member-as-private encapsulation. You should have a reason to make a member public or private, there is no by default rule.
    – masoud
    Commented Nov 24, 2013 at 21:49

8 Answers 8

6

There exist many reasons why you would want to use properties (getters and setters) instead of public fields (instance variables made public). Some of them are:

  • You can allow read-only access to external classes (by providing a getter, but not a setter)
  • You can calculate the value when it is accessed.
  • You can change how the value is accessed/calculated without breaking existing code.
  • You can change the internal representation without breaking existing code.
  • You can override properties in subclasses, which is not possible with fields.
  • Etc.

Also, there aren't really that many downsides to using properties. So the pros outweigh the cons.

2
  • Right! So when it's a field you can do whatever you want with it, but when you have a setter and a getter you can do less (only set/get the value) but also much more (do different operations with it for example). Thanks!
    – Bonnev
    Commented Nov 24, 2013 at 21:45
  • 3
    .. if the setter/getter as you're describing them, do not special thing then you can omit them and use public members, but, many programmers in this case still use setter/getter to keep the code uniform.
    – masoud
    Commented Nov 24, 2013 at 21:52
2

The answer differs for different languages.

In C++ it is a good idea to make attributes private and provide getter and setter methods because C++ provides const correctness - and setters cannot be called on a const object.

In C# which does not offer const correctness it may seem pointless to do other than simply offer all attributes up as public, as the moment there is a setter it can be called at any time anyway.

But what if, for example, the property is a container (List, for example). It might then be that you only want people to be able to manipulate the list but not set the list pointer to a new value - so you would define the property like this:

class Contrived
{
    private List<Things> m_List = new List<Things>();

    public List<Things> LIST{ get {return m_List;} }
};

Or maybe you only want people to be able to examine the list, but not add or remove things from it:

class Contrived
{
    private List<Things> m_List = new List<Things>();

    public IEnumerable<Things> LIST{ get {return m_List;} }
};

In that way we are staggering towards faking const correctness by use of interfaces, although IMO it's not as good as just having a const correct language. ;-) Indeed, in the last example we provide a list that cannot be modified but who's contents can be, so we could implement the property like this (assuming Things implements IUnmoddableThing):

class Contrived
{
    private List<Things> m_List = new List<Things>();

    public IEnumerable<IUnmoddableThing> LIST{ 
    get 
    {
        List<IUnmoddableThing> temp = new List<IUnmoddableThing>();
        ... copy m_List into temp ...
        return temp;
    } }
};

Clearly allowing us much more control than simply making the member attribute public. And that's before we get into a property hiding the fact that we actually, maybe ... oh, connect to a remote database, via a socket, carried by a bespoke military radio...

Once you realise that a setter can be denied use at compile time (in a const correct language) and that a getter/setter or get/set (depending on language) can do more than simply assign or return, they can be very powerful.

1

scoping - that is public and private for example is a way to tell people how to use your class

Anything public (or protected in C++) is part of your contract with users of your class

What that means is:

you should not change anything public

you can freely change anything that is private as that is considered an implementation detail of your class

1

Such behavior is widely acknowledged as 'good programming manners' so as to always present the class user an interface that he can freely use without concern of breaking anything inside it. This is mainly why one should close changing class properties in an accessor like methods. It's extremely useful when changing a field changes also some other field and has an influence on the class. Besides, it comes in handy when you're trying to find that one moment when someone is changing a field value that breaks something ;)

1

Well, what if you wanted to later change that property to a database call? That wouldn't be possible with a field. Also, what if you don't want the property to be settable from outside of the class, but not inside? What if you want to change it so that you an only set non-null values? Can you get a notification when the value is changed? You can't do any of those with a field, and all with getters+setters.

1

This is call encapsulation and allows you to properly manage access to your class information: Encapsulation

Encapsulation is not always needed but strongly recommended to hide your class internals and prevent unappropriated data management, for example, you can add some checks to your setter that, if data is public, you cannot prevent:

int SomeClass::setPointer(char *point)
{
   if(!point)
   {
      cout << "Trying to assign null pointer" << endl; //Or, better, throw exception
      return error; // Or, better, throw exception
   }
   mPointer = point;
}

This is most basic advantage, but there should be other like:

  • You can automatically update related control data every time main data is modified (e.g. array size every time new elements are added).
  • Style: it is easier to maintain (e.g. you change member's type and yo only need to add a cast in the setter, instead to modify all lines that calls this field)
  • Increases usability
  • In some cases, better performance.
  • etc.
0

Lots of good reasons for encapsulation have been listed by other answers. I just want to add the one reason which is most fundamental:

  • protecting the invariants of your class

If your class is designed to maintain some invariant, you must not give users of your class any means of breaking it. For example, if you design a container, it would be unwise to give the user write access to something like capacity and size.

-1

Furthermore, the values of data members in a class are rarely independent, direct access(change the value) to the data will easily leave an object in an inconsistent state.

Not the answer you're looking for? Browse other questions tagged or ask your own question.