2.6.6 Initializing Required Object State

Initializing Required Object State

A TrainingArea should be ready to answer questions as soon as creation finishes. Decide which values are fixed defaults and which information the caller must supply.

Initialize a usable starting state
Soccer example
public class TrainingArea
{
    private string name;
    private double temperature;

    public TrainingArea(string name)
    {
        this.name = name;
        this.temperature = 20.0;
    }

    public string GetName()
    {
        return this.name;
    }

    public double GetTemperature()
    {
        return this.temperature;
    }
}

The caller supplies a name because areas can have different names. The class supplies the common starting temperature. Both assignments happen before the new expression finishes. This minimal version isolates initialization from later temperature actions.

Do not confuse default values with required values
Caller method
TrainingArea area = new TrainingArea("Wildcats practice area");
double initialTemperature = area.GetTemperature();

initialTemperature is 20.0. Without the authored assignment, a double field would initially be 0.0. That is a legal C# default but not this application starting value.

Apply the idea
Check your understanding