Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

c# - Should I use set once variables?

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 this.

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

But I don't like it. I feel like I have missed something. Have I?

Edit: Why I don't have it in the constructor.
I cant go into the details but setting this results in <bad analogy> Melting the wax statue </bad analogy>. And I don't want my constructor to create already melted objects.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...