HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

When one property is calculated from another

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
onepropertyanotherwhenfromcalculated

Problem

I've got a class with a property TotalCost, which is calculated by some simple math of two other properties, CostOfFood and NumberOfPeople. The code works the way I want it to, but I was wondering if this is a satisfactory method in the long run of application development, a bad idea to have one property that depends on another all together (I'm pretty sure this is the case, but sometimes it makes sense to), or if the informed reader would deem it acceptable. Helpful hints are in the comments.

```
class DinnerParty
{
private int numberOfPeople;
public int NumberOfPeople
{
get { return numberOfPeople; }
set
{
numberOfPeople = value;
//TotalCost property is updated when more people are added to the party
TotalCost =CalculateFoodCost(value);
}
}
private decimal totalCost;

public decimal TotalCost
{

get { return totalCost; }
private set
{
totalCost = value;
}
}

private decimal costOfFood;
public decimal CostOfFood
{
get { return costOfFood; }
set
{
costOfFood = value;
//TotalCost property is updated when CostOfFood changes
//directly below line was my initial idea
//TotalCost = value * NumberOfPeople was my initial thought
//before overloading the CalculateFoodCost method

//this calls the CalculateFoodCost version that takes a decimal
TotalCost = CalculateFoodCost(value);
}
}
private decimal CalculateFoodCost(int costOfFood)
{
//the int coming in as a parameter is the 'value' of the NumberOfPeople property
return this.costOfFood * NumberOfPeople;

}
private decimal CalculateFoodCost(decimal costOfFood)
{
return this.costOfFood * NumberOfPeople;
}

public DinnerParty()
{
//so food cost is never 0
CostOfFood

Solution

The C# property model allows external classes to inspect (or set) a given member as though it were a public 'field', and the implementation details are left to the property's accessor and mutator. In your case, you want to expose TotalCost and hide the implementation details about how it is derived. And your code reflects best practices.

Following the comment from Clockwork-Muse, your implementation can be made more elegant by...

public decimal TotalCost
    {
        get { return CostOfFood * NumberOfPeople; }
    }


This avoids the calculation penalty for setting either of the calculation ingredients and performs the calculation only when called upon to do so. It's also a bit more readable and transparent. In this particular case, there's no need for an asymmetric mutator, so it's been removed.

Code Snippets

public decimal TotalCost
    {
        get { return CostOfFood * NumberOfPeople; }
    }

Context

StackExchange Code Review Q#28609, answer score: 20

Revisions (0)

No revisions yet.