Definition of public property

What are the benefits of defining a property for an object instead of directly accessing a private variable?

Instead:

public class A private _x as integer = 0 Public property X() as integer Get return _x End Get Set(ByVal value As integer) _x = value End Set End Property end class 

Why can't we do the following:

 public class A public _x as integer = 0 end class 

What are the benefits?

+4
source share
2 answers

One of the advantages is that a number of frameworks look for class properties for binding purposes, and not for fields. Therefore, directly displaying the _x field causes some headaches when you wonder why the infrastructure is not setting the value, as you might expect.

Also, because of encapsulation, you can change what happens when a code call interacts with a field. Hiding the field behind the getter / setter object allows you to perform additional actions, such as starting when the value changes, updating another internal state, or completely changing the implementation, so this is just a call to the child object.

+5
source

The main reason is that later you can add behavior (logging, validation, database, etc.) to the property without changing the ABI (Application Binary Interface). If you defined it as a field, then you wanted to add behavior, you will need to change the property (or method). Any of these will require recompiling another code (and modified if you sent the method route).

+1
source

Source: https://habr.com/ru/post/1315024/


All Articles