Should I use set once variables?

后端 未结 8 709
闹比i
闹比i 2020-12-21 05:27

Does this smell?
I have a few properties you can only set once. They can be set at any time during the objects existence and can not be undone.
I implement then like

相关标签:
8条回答
  • 2020-12-21 05:33

    I think the design would be more clear to the caller if such values are passed to the constructor, and exposed as read-only properties instead. If the value can't be set at construction time, perhaps it could be appropriate to throw an exception if trying to set the value again:

    private FooThingy _foo;
    public FooThingy Foo
    {
        set 
        { 
            if (null == _foo) { _foo = value; }
            else  { throw new WhatEverThatFitsException(); }
        }
        get { return _foo; }
    }
    

    Just to be very clear: I do not in any way promote the use of set-once properties; the code sample only show the approach that I might use, should the value not be available at construction time of the object for whatever reason. That said; I have never come across that situation in any of the projects I have been involved in.

    0 讨论(0)
  • 2020-12-21 05:36

    if FooThingy is a value object like an int it will be 0 initialized instead of null. For the rest it looks okay

    0 讨论(0)
  • 2020-12-21 05:40

    Make them readonly and set them in the constructor.

    0 讨论(0)
  • 2020-12-21 05:41

    I agree with Fredrik, readonly would make more sense. This way you could only declare your variable in the constructor (or as part of the declaration). I think doing what your doing isnt instantly clear that this is what you want to achieve.

    Check out this MSDN page.

    0 讨论(0)
  • 2020-12-21 05:42

    It's hard to tell from this toy example, but it sounds like _foo is relatively important to the existence of this object. In that case, it should almost certainly be a readonly property which is initialized at creation time, and not have any public setter. Favor immutable objects wherever possible; it makes your life much simpler!

    0 讨论(0)
  • 2020-12-21 05:52

    I would suggest setting them on construction, and therefore making the setters private. That seems like a more sensible way.

    If you are going to do it that way, throw some sort of Exception. At least let the developer know you didn't set their values rather than ignoring it silently.

    0 讨论(0)
提交回复
热议问题