Access a class member from a class

When accessing properties inside a class, should you use a private member variable or a public property?

+6
source share
5 answers

Actually there is an answer to this question, but I believe that he only received it by asking another:

Get the desired behavior from using a variable or property?

Often a property performs data operations, that is, you cannot get exact values ​​from one to another. As a rule, they don’t do anything “expensive” and do not produce side effects that appear in other shadow-related elements of the class (properties should not do this), but one of the advantages of the properties is the presence of a “mask”, therefore speaking, providing the desired behavior when receiving and tuning, which may differ from a direct return or destination, where the variables are raw, genuine data, this is what you will need to look for.

For example, you can find a property for X never returns null, but the base variable can be, and sometimes even null - in this case, your operations may depend on checking the null value, while the property provides a "safe bet" on the street. Therefore, you must work with the main element in this particular case.

Obviously, you should strive for some model of coherence in this practice, but the above principle and practice will be mainly dictated for each decision, project or even class!

+3
source

If this is something that has a public property that has a setter, I would use this (everything else was equal).

+1
source

In general, from within your class, when there is a property that also applies to a private variable, use a private variable from your class. This is an implementation detail. The purpose of this property is a stable external interface.

BUT, if your property really uses some smart things that you depend on (for example, a dependency property), you can always use the property to reuse this intelligence.

At the very least, keep an eye on what you are doing, of course, within the framework of one class so that your implementation is understandable and supported.

+1
source

In most cases, access to a private field.

In the MVVM view model or any other class that implements INotifyPropertyChanged (or a similar situation when this is required in the context), you must access public properties so that subscribers notify about the value change.

0
source

It depends if the property has any logic: Similar to checking input in the setter, or returning a standard value or the like upon receipt.

And only for these arguments I would suggest using a property. And, as always, it is wise to use privacy / public.

0
source

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


All Articles