Should I use set once variables?

后端 未结 8 710
闹比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:59

    Set-once-properties violate the principle of least surprise - a caller expects that when a property can be set once, it can be set again. (barring range and compatibility checks, of course - but they are bound to specific values or value combinations).

    Initialize them in the constructor.
    Alternatively, if they are to many / to complex to write all constructors, use a factory/builder class:

    ThingieBuilder tb = new ThingieBuilder();
    tb.FooThingy = 17.23;   // r/w properties
    tb.BarThingy = 42;
    tb.UseExtendedThingamagicAdapter = true;
    Thingie t = tb.Create();
    if (t.Bar==42) // r/o property
      ...
    

    Or, separate the settings in a configuration object, that can be replaced or passed during construction.

    0 讨论(0)
  • 2020-12-21 06:00

    Just make the setters methods and not properties - and the disconnect between expectation and behavior goes away. The method is free to throw an InvalidOperationException - but it's unexpected to have a property setter do it.

    private FooThingy _foo;
    public FooThingy Foo
    {
        get { return _foo; }
    }
    
    public void SetFooThingy(FooThingy value) {
       if (Foo != null) 
          throw new InvalidOperationException("Foo is already set!");
       _foo = value;
    }
    
    0 讨论(0)
提交回复
热议问题