K
K
kos_dev2019-08-10 03:32:17
OOP
kos_dev, 2019-08-10 03:32:17

What is better to use in real projects Properties or Protected variables and methods to them?

Hello, tell me what and when is better to use and what am I wrong about:
Properties (I believe that they should be used if you need to get the field value outside the class)
or
Protected field (apparently it is used when you do not need to get the field value outside class) and, if we still need its value, then the methods for this field, example below

class A
    {
        protected int v1; // protected

        public void setV1(int val)
        {
            if (val < 0) v1 = -1;
            else v1 = val;
        }
        public int getV1() { return v1; }


        private int _v2;
        public int v2 // prop
        {
            get
            {
                return _v2;
            }
            set
            {
                if (value < 0)
                    _v2 = -1;
                else _v2 = value;
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#, 2019-08-10
@kos_dev

the getter/setter fashion just seems to be going away.
the very trick of the getter and setter is that in them, as if by a trigger, you can do incidental actions. most often validation or logging, but there may be more ingenious ties . the
issue of field security is completely independent. it is necessary to separately study when and why to hide fields from other classes (private) or assemblies (protectet)
it is worth considering that this has nothing to do with hiding code at all. but more than important for creating thread -safe classes/methods

V
Vladev, 2019-08-10
@Vladev

Properties. The example with protected is shit code from C++, where there are no properties.
If the field is protected, then it is understood that it can be directly changed from all classes that are in this namespace.
If you want the field to change directly from everywhere, then this is a public variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question