Sam
Sam

Reputation: 7398

Should a property's value be calculated within a class or left to the caller?

Lets say I have an immutable class with a few properties, some of which can be calculated from with in the class, now, I could let the caller calculate the value of each property, or, I could let the class calculate each the properties itself.

For example, in the class below A must be defined. B & C's values can be calculated from A.

Letting the caller define the properties,

class Z
{
    public int A { get; private set; }

    public int B { get; private set; } 

    public int C { get; private set; } 



    public Z(int a, int b, int c)
    {
        A = a; // Must always be explicitly defined.
        B = b; // Explicit definition is optional.
        C = c; // Explicit definition is optional.
    }
}

Letting the class define as many properties as possible,

class Z
{
    public int A { get; private set; }

    public int B { get; private set; }

    public int C { get; private set; } 



    public Z(int a)
    {
        A = a; // Must always be explicitly defined.
        B =    // Calculation logic involving A...
        C =    // More calculation logic involving A...
    }
}

So are there any conventions stating when/where to use one method over the other (and why)?

Upvotes: 0

Views: 342

Answers (3)

Servy
Servy

Reputation: 203821

You should go with the second approach. It seems pretty clear in this case that computing these derived values is the responsibility of this class. By requiring the caller of the class to do the computations and provide the data to this class it allows the possibility for the class to end up in an invalid state; when it computes the values itself it is able to ensure that it is never in an invalid state.

Upvotes: 2

Kamil T
Kamil T

Reputation: 2216

I'd say that the best way would be something like this:

class Z
{
    public int A { get; private set; }
    public int B { get {return a*a;} }
    public int C { get {return b*a;} } 



    public Z(int a)
    {      
        A = a; // Must always be explicitly defined.
    }
}

In this case you don't need setters for B and C and you have a getter for them which neatly calculates the value. You also evaluate B and C only when it is needed.

Upvotes: 2

Steven Wood
Steven Wood

Reputation: 2775

couldnt you do the following:

class Z
{
    private int a;
    public int A { get; 
                   private set
                   {
                      a = value;
                      B = //calculation
                      C = //calculation
                   } 
                 }

    public int B { get; private set; } 
    public int C { get; private set; } 



    public Z(int a)
    {
        A = a; // Must always be explicitly defined.
    }
}

Upvotes: 1

Related Questions