Why not use class fields directly?

So, I know that classes and structures are data structures. Class fields are private by default and structural are public. Both public: / int a;for C ++ and public int a;C #

But other ways to access these fields are that they are private and use functions / methods. How SetValue(int value){a = value;}and GetValue() { return a; }or I even heard about a cool new {set; get;}in C #.

But why? Many people have told me that "other people can access your variables this way, so make them private." I donโ€™t understand what difference makes them public and just uses them obj.a = 3;or makes them private and makes obj.SetValue(3);? Can someone (at least briefly) explain what the differences are and how so can get into these fields when they are open?

+4
source share
8 answers

There are many reasons why you would like to use properties (getters and setters) instead of public fields (instance variables have been published). Some of them:

  • ( , ).
  • .
  • / .
  • , .
  • , .
  • Etc.

, . , .

+5

.

++ private getter setter, ++ - const-.

#, const-, , , , , .

, , , (, List). , , , :

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

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

, , , , :

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

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

, , , .;-) , , , , , (, Things 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;
    } }
};

, , member. , , , , ... , , ...

, ( ) getter/setter get/set ( ) , , .

+2

: Encapsulation

, , , , , , :

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;
}

, :

  • (, ).
  • : (, , , , )
  • .
  • .
+1

scoping - , , ,

( ++)

:

, , .

+1

" ", , , , - . , . , . , , , - , - ;)

+1

, ? . , , , , ? , , ? ? , getters + seters.

+1

. :

, - . , , - capacity size.

0

, , ( ) .

-1

All Articles