I am trying to decide between two designs of a class. The basic difference is the one calculates properties when they are called, and the other when the object is instantiated.
I would usually just take the first one, but the calculations call each other, so when calling all of them, they get recalculated multiple times.
I, however, still prefer the first code. It is cleaner. Easier, for me, to read. I also feel the calculations are probably small enough to not worry about as opposed to storing extra values.
Is there anything else I should be considering, or looking out for? Or any reason one is amazingly better than the other?
public class Angle1
{
private decimal angle;
public int Degree => (int)Math.Floor(angle);
private decimal MinuteSecond => (angle - Degree) * 60;
public int Minute => (int)Math.Floor(MinuteSecond);
public decimal Second => (MinuteSecond - Minute) * 60;
public Angle1(decimal angle)
{
this.angle = angle;
}
}
public class Angle2
{
private decimal angle;
public int Degree { get; private set; }
public int Minute { get; private set; }
public decimal Second { get; private set; }
public Angle2(decimal angle)
{
this.angle = angle;
Degree = (int)Math.Floor(angle);
var minSec = (angle - Degree) * 60;
Minute = (int)Math.Floor(minSec);
Second = (minSec - Minute) * 60;
}
}
I have also thought of a "hybrid" option. Store values in private values. When a property is called the first time, the value is calculated, and the private value is set. When it is called again, the private value is returned.
This hybrid option is the one I naturally go to when properties are larger objects, datasets, or binary data. I feel in this instance, it would "dirty" the code more than necessary, for the size of the stored values (integers and decimals).