JCompiler JCompiler - 3 months ago 19
C# Question

Creating a Temperature class which supports different units (Celsius, Fahrenheit, Kelvin)

I'm working on a class to help me to convert between units, and I need to ask about the best way to create this work.

This is my sample code about temperature:

public class Temperature
{
private double _Celsius = 0;
public double Celsius
{
get { return _Celsius; }
set
{
_Fahrenheit = (value * 9 / 5) + 32;
_Kelvin = value + 273.15;
}
}
private double _Fahrenheit = 0;
public double Fahrenheit
{
get { return _Fahrenheit; }
set
{
_Celsius = (value - 32) * 5/9;
_Kelvin = _Celsius + 273.15;
}
}
private double _Kelvin = 0;
public double Kelvin
{
get { return _Kelvin; }
set
{
_Celsius = value - 273.15;
_Fahrenheit = (_Celsius * 9 / 5) + 32;
}
}
}


I hope to know if there is another good one for this class or not?

Answer

Why do you have three fields _Celsius, _Fahrenheit, _Kelvin when just one (say, _Celsius) is enough:

  public class Temperature {
    private double _Celsius

    public double Celsius {
      get {
        return _Celsius;
      }
      set {
        // Simplest: no validation (e.g. -500 degree is an evident error)
        _Celsius = value;
      } 
    }

    public double Kelvin {
      get { 
        return Celsius + 273.15;
      }  
      set {
        Celsius = value - 273.15;
      } 
    }

    public double Fahrenheit {
      get { 
        return Celsius * 9 / 5 + 32;
      }  
      set {
        Celsius = (value - 32) * 5 / 9;
      } 
    }
  } 

Now let's think on what is the expected way of using your routine? E.g. I want to convert 100 Fahrenheit to Kelvin:

  double result = new Temperature() { Fahrenheit = 100.0 }.Kelvin;

a bit wordy and counter-intuitive, right? May be a better choice is to implement a bunch of static methods? And do not create any class at all?

  public static class Temperatures {
    public static double FahrenheitToCelsius(double value) {...} 

    public static double CelsiusToKelvin(double value) {...}

    public static double FahrenheitToKelvin(double value) {
      return CelsiusToKelvin(FahrenheitToCelsius(value)); 
    }
    ...
  } 

  ...

  double result = Temperatures.FahrenheitToKelvin(100.0);