什么时候确定的属性getter访问更改(例如初始化)对象状态?(When is it ok to c

2019-10-18 09:14发布

(except for proxy setup!)

I spent some time writing a question here regarding a better pattern for a problem I had - of a class that performed some conditional initialization on almost every property getter, since the initialization in the base class relied on data from the inheriting classes that wasn't available on construction.

While writing the question I came to the conclusion it would be better practice to initialize on inheritor construction. This would require every inheriting class to call the parents initialization method, but I think it's better, because:

  1. I don't have to remember to initialize in the base class on every new property getter/setter.
  2. I don't accidentally trigger the initialization while debugging (see my question here)

If you ever had code that changes state in a property getter, do you think it's absolutely justified? Can you give an example for such a case? (Or even describe the pattern?)

I could only think of proxy access, where you don't want to perform initialization until property access...


Somebody suggested that I initialize using a factory/static method - that's actually a good idea (when the construction is simple, a bit harder when it's not uniform across inheriting classes), but the answer was deleted before I had a chance to submit my reply. too bad.

Answer 1:

懒惰缓存。 当你不直到访问该属性从数据库加载数据。 (不知道这是你通过代理访问的意思)。

不过,我不会真的认为这是逻辑上改变对象的类的行为的状态保持前和访问后相同。 该数据暗示有在任何时候。 逻辑状态保持不变。

因为它是反直觉和逻辑上不正确我绝不会通过一个getter改变类的逻辑状态。 你做冒险的种种意想不到的后果..

你可以做类似如下:

    public class baseone
    {
        private baseone ()
        {
        }

        public baseone ( string huh )
        {
                initialise(huh);
        }

            protected abstract initialise(string stuff); 
    }


    public class niceone : baseone
    {
        public niceone (string param)
         : base(param)
        {

        }

            protected override initialise(string stuff)
            {
               // do stuff..
            }
    }

使基类私有的默认构造函数确保所需的参数必须传递给初始化类。



文章来源: When is it ok to change object state (for instance initialization) on property getter access?