Home > Blockchain >  How to set initialization order for a properties object?
How to set initialization order for a properties object?

Time:05-18

Ex: suppose I have

    private double foo;
    private double bar;

    public double foo
    {
        get { return foo; }
        set
        {
            foo = value;
        }
    }

    public double bar
    {
        get { return bar; }
        set
        {
            
            bar = value * foo ;
        }
    }

When this object is initialized I want to set the order in that someone first sets a value to foo, then sets a value to bar. I know that I can throw an exception if foo is not initialized within bar but is there a way to set this requirement so whoever instantiates this properties object this will not have any issues to begin with?

CodePudding user response:

I would argue that public setter are not appropriate in this particular case. I would suggest using a constructor instead:

public MyClass(double foo, double value) => (Foo, Bar) = (foo, value*foo);
public double Foo {get; private set;}
public double Bar {get; private set;}

Note that I did not call the parameter bar, since that would lead to the expectation that the Bar-property should have the value of the bar parameter.

You might opt to give Bar a default value if you wish. But in general, the constructor should ensure that the type is fully constructed, so any required properties should be injected as constructor parameters.

I would in general not expect that a setter has any complex behavior. Common logic would be things like range checking or to update things that depend on the property. If you need some more complex logic you could add it as a method, this give a hint that the method does more than just setting a property:

public void SetBar(double value) => Bar = value * foo;

Or use a separate property that calculates foo*bar:

public MyClass(double foo, double bar) => (Foo, Bar) = (foo, bar);
public double Foo {get; set;}
public double Bar {get; set;}
public double FooBar => Foo * Bar;

This would by far be my preferred solution since it would be very difficult to get this kind of code wrong. It should be perfectly obvious what all properties does.

  • Related