Refactoring; creating pseudo-primitives for your application domain

How would you reorganize this, bearing in mind that you have dozens more of these dimensions? It's like changing an int to short or long or byte. General unit<T>

? Implicit type conversion through operator overloading? ToType()

template? An abstract base class? IConvertible

?

public class lb
{
    private readonly float lbs;
    private readonly kg kgs;

    public lb(float lbs)
    {
        this.lbs = lbs;
        this.kgs = new kg(lbs * 0.45359237F);
    }

    public kg ToKg()
    {
        return this.kgs; 
    }

    public float ToFloat()
    {
        return this.lbs;
    }
}

public class kg 
{
    private readonly float kgs;
    private readonly lb lbs;

    public kg(float kgs)
    {
        this.kgs = kgs;
        this.lbs = new lb(kgs * 2.20462262F);
    }

    public float ToFloat()
    {
        return this.kgs;
    }

    public lb ToLb()
    {
        return this.lbs;
    }
}

      

+1


source to share


2 answers


I would not create separate classes for each weight. Instead, you have one class that represents one and another that represents a number with one:

/// <summary>
/// Class representing a unit of weight, including how to
/// convert that unit to kg.
/// </summary>
class WeightUnit
{
    private readonly float conv;
    private readonly string name;

    /// <summary>
    /// Creates a weight unit
    /// </summary>
    WeightUnit(float conv, string name)
    {
        this.conv = conv;
        this.name = name;
    }

    /// <summary>
    /// Returns the name of the unit
    /// </summary>
    public string Name { get { return name; } }

    /// <summary>
    /// Returns the multiplier used to convert this
    /// unit into kg
    /// </summary>
    public float convToKg { get { return conv; } }
};

/// <summary>
/// Class representing a weight, i.e., a number and a unit.
/// </summary>
class Weight
{
    private readonly float value;
    private readonly WeightUnit unit;

    public Weight(float value, WeightUnit unit)
    {
        this.value = value;
        this.unit = unit;
    }

    public float ToFloat()
    {
        return value;
    }

    public WeightUnit Unit
    {
        get { return unit; }
    }

    /// <summary>
    /// Creates a Weight object that is the same value
    /// as this object, but in the given units.
    /// </summary>
    public Weight Convert(WeightUnit newUnit)
    {
        float newVal = value * unit.convToKg / newUnit.convToKg;

        return new Weight(newVal, newUnit);
    }
};

      



The nice thing is that you can create all WeightUnits as singleton objects from data, perhaps an XML file or resource, so you can add a new module without changing any code at all. Creating a Weight object is a matter of finding the correct single name by name.

+4


source


I think I'll just turn it into struct

, which most primitives have anyway.



0


source







All Articles