<p>Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter?</p>

<p>Example 1 - separate parameters:
function convertTemperature("celsius", "fahrenheit", 22)</p>

<p>Example 2 - combined parameter:
function convertTemperature("c-f", 22)</p>

<p>The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow.</p>

<p>Thoughts?</p>

[{'answer_id': 59108, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 5, 'selected': True, 'text': '<p>Go with the first option, but rather than allow literal strings (which are error prone), take constant values or an enumeration if your language supports it, like this:</p>\n\n<pre><code>convertTemperature (TempScale.CELSIUS, TempScale.FAHRENHEIT, 22)\n</code></pre>\n'}, {'answer_id': 59110, 'author': 'Kilhoffer', 'author_id': 5469, 'author_profile': 'https://Stackoverflow.com/users/5469', 'pm_score': 0, 'selected': False, 'text': '<p>My vote is two parameters for conversion types, one for the value (as in your first example). I would use enums instead of string literals, however.</p>\n'}, {'answer_id': 59112, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 0, 'selected': False, 'text': "<p>Use enums, if your language allows it, for the unit specifications.</p>\n\n<p>I'd say the code inside would be easier with two. I'd have a table with pre-add, multiplty, and post-add, and run the value through the item for one unit, and then through the item for the other unit in reverse. Basically converting the input temperature to a common base value inside, and then out to the other unit. This entire function would be table-driven.</p>\n"}, {'answer_id': 59117, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 1, 'selected': False, 'text': "<p>Depends how many conversions you are going to have. I'd probably choose one parameter, given as an enum: Consider this expanded version of conversion.</p>\n\n<pre><code>enum Conversion\n{\n  CelsiusToFahrenheit,\n  FahrenheitToCelsius,\n  KilosToPounds\n}\n\nConvert(Conversion conversion, X from);\n</code></pre>\n\n<p>You now have sane type safety at point of call - one cannot give correctly typed parameters that give an incorrect runtime result. Consider the alternative.</p>\n\n<pre><code>enum Units\n{\n  Pounds,\n  Kilos,\n  Celcius,\n  Farenheight\n}\n\nConvert(Unit from, Unit to, X fromAmount);\n</code></pre>\n\n<p>I can type safely call</p>\n\n<pre><code>Convert(Pounds, Celcius, 5, 10);\n</code></pre>\n\n<p>But the result is meaningless, and you'll have to fail at runtime. Yes, I know you're only dealing with temperature at the moment, but the general concept still holds (I believe).</p>\n"}, {'answer_id': 59118, 'author': 'DaveK', 'author_id': 4244, 'author_profile': 'https://Stackoverflow.com/users/4244', 'pm_score': 1, 'selected': False, 'text': '<p>I would make an enumeration out of the temperature types and pass in the 2 scale parameters. Something like (in c#):</p>\n\n<p><pre><code>\npublic void ConvertTemperature(TemperatureTypeEnum SourceTemp,\n                               TemperatureTypeEnum TargetTemp, \n                               decimal Temperature)\n{}\n</pre></code></p>\n'}, {'answer_id': 59123, 'author': 'millenomi', 'author_id': 6061, 'author_profile': 'https://Stackoverflow.com/users/6061', 'pm_score': 2, 'selected': False, 'text': "<p>A few things:</p>\n\n<ul>\n<li><p>I'd use an enumerated type that a syntax checker or compiler can check rather than a string that can be mistyped. In Pseudo-PHP:</p>\n\n<p>define ('kCelsius', 0); define ('kFarenheit', 1); define ('kKelvin', 2);\n$a = ConvertTemperature(22, kCelsius, kFarenheit);</p></li>\n</ul>\n\n<p>Also, it seems more natural to me to place the thing you operate on, in this case the temperature to be converted, <em>first</em>. It gives a logical ordering to your parameters (convert -- what? from? to?) and thus helps with mnemonics.</p>\n"}, {'answer_id': 59124, 'author': 'Paul Stephenson', 'author_id': 5536, 'author_profile': 'https://Stackoverflow.com/users/5536', 'pm_score': 1, 'selected': False, 'text': '<p>I would choose </p>\n\n<blockquote>\n  <p>Example 1 - separate parameters: function convertTemperature("celsius", "fahrenheit", 22)</p>\n</blockquote>\n\n<p>Otherwise within your function definition you would have to parse "c-f" into "celsius" and "fahrenheit" anyway to get the required conversion scales, which could get messy.</p>\n\n<p>If you\'re providing something like Google\'s search box to users, having handy shortcuts like "c-f" is nice for them.  Underneath, though, I would convert "c-f" into "celsius" and "fahrenheit" in an outer function before calling convertTemperature() as above.</p>\n'}, {'answer_id': 59126, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 1, 'selected': False, 'text': "<p>In this case single parameters looks totally obscure;</p>\n\n<p>Function convert <em>temperature</em> from <em>one scale</em> to <em>another scale</em>.<br>\nIMO it's more natural to pass source and target scales as separate parameters. I definitely don't want to try to grasp format of first argument.</p>\n"}, {'answer_id': 59131, 'author': 'Rob Rolnick', 'author_id': 4798, 'author_profile': 'https://Stackoverflow.com/users/4798', 'pm_score': 2, 'selected': False, 'text': '<p>When writing such designs, I like to think to myself, "If I needed to add an extra unit, what would design would make it the easiest to do so?" Doing this, I come to the conclusion that enums would be easiest for the following reasons:</p>\n\n<p>1) Adding new values is easy.\n2) I avoid doing string comparison</p>\n\n<p>However, how do you write the conversion method? 3p2 is 6. So that means there are 6 different combinations of celsius, Fahrenheit, and kelvin. What if I wanted to add a new temperate format "foo"? That would mean 4p2 which is 12! Two more? 5p2 = 20 combination. Three more? 6p2 = 30 combinations! </p>\n\n<p>You can quickly see how each additional modification requires more and more changes to the code. For this reason I don\'t do direct conversions! Instead, I do an intermediate conversion. I\'d pick one temperature, say Kelvin. And initially, I\'d convert to kelvin. I\'d then convert kelvin to the desired temperature. Yes, It does result in an extra calculation. However, it makes scalling the code a ton easier. adding adding a new temperature unit will always result in only two new modifications to the code. Easy.</p>\n'}, {'answer_id': 59137, 'author': 'Isaac Moses', 'author_id': 179, 'author_profile': 'https://Stackoverflow.com/users/179', 'pm_score': 2, 'selected': False, 'text': "<p>Your function will be much more robust if you use the first approach. If you need to add another scale, that's one more parameter value to handle. In the second approach, adding another scale means adding as many values as you already had scales on the list, times 2. (For example, to add K to C and F, you'd have to add K-C, K-F, C-K, and C-F.)</p>\n\n<p>A decent way to structure your program would be to first convert whatever comes in to an arbitrarily chosen intermediate scale, and then convert from that intermediate scale to the outgoing scale.</p>\n\n<p>A better way would be to have a little library of slopes and intercepts for the various scales, and just look up the numbers for the incoming and outgoing scales and do the calculation in one generic step.</p>\n"}, {'answer_id': 59142, 'author': 'Adam Davis', 'author_id': 2915, 'author_profile': 'https://Stackoverflow.com/users/2915', 'pm_score': 3, 'selected': False, 'text': "<p>Depends on the language.</p>\n\n<p>Generally, I'd use separate arguments with enums.</p>\n\n<p>If it's an object oriented language, then I'd recommend a temperature class, with the temperature stored internally however you like and then functions to output it in whatever units are needed:</p>\n\n<p>temp.celsius();  // returns the temperature of object temp in celsius</p>\n"}, {'answer_id': 59176, 'author': 'Jay Bazuzi', 'author_id': 5314, 'author_profile': 'https://Stackoverflow.com/users/5314', 'pm_score': 1, 'selected': False, 'text': "<p>I'm always on the lookout for ways to use objects to solve my programming problems.  I hope this means that I'm more OO than when I was only using functions to solve problems, but that remains to be seen.</p>\n\n<p>In C#:</p>\n\n<pre><code>interface ITemperature\n{\n     CelciusTemperature ToCelcius();\n     FarenheitTemperature ToFarenheit();\n}\n\nstruct FarenheitTemperature : ITemperature\n{\n    public readonly int Value;\n    public FarenheitTemperature(int value)\n    {\n        this.Value = value;\n    }\n\n    public FarenheitTemperature ToFarenheit() { return this; }\n    public CelciusTemperature ToCelcius()\n    {\n        return new CelciusTemperature((this.Value - 32) * 5 / 9);\n    }\n\n}\n\nstruct CelciusTemperature\n{\n    public readonly int Value;\n    public CelciusTemperature(int value)\n    {\n        this.Value = value;\n    }\n\n    public CelciusTemperature ToCelcius() { return this; }\n    public FarenheitTemperature ToFarenheit()\n    {\n        return new FarenheitTemperature(this.Value * 9 / 5 + 32);\n    }\n}\n</code></pre>\n\n<p>and some tests:</p>\n\n<pre><code>        // Freezing\n        Debug.Assert(new FarenheitTemperature(32).ToCelcius().Equals(new CelciusTemperature(0)));\n        Debug.Assert(new CelciusTemperature(0).ToFarenheit().Equals(new FarenheitTemperature(32)));\n\n        // crossover\n        Debug.Assert(new FarenheitTemperature(-40).ToCelcius().Equals(new CelciusTemperature(-40)));\n        Debug.Assert(new CelciusTemperature(-40).ToFarenheit().Equals(new FarenheitTemperature(-40)));\n</code></pre>\n\n<p>and an example of a bug that this approach avoids:</p>\n\n<pre><code>        CelciusTemperature theOutbackInAMidnightOilSong = new CelciusTemperature(45);\n        FarenheitTemperature x = theOutbackInAMidnightOilSong; // ERROR: Cannot implicitly convert type 'CelciusTemperature' to 'FarenheitTemperature'\n</code></pre>\n\n<p>Adding Kelvin conversions is left as an exercise.</p>\n"}, {'answer_id': 59201, 'author': 'wcm', 'author_id': 2173, 'author_profile': 'https://Stackoverflow.com/users/2173', 'pm_score': 2, 'selected': False, 'text': '<p>In C# (and probaly Java) it would be best to create a Temperature class that stores temperatures privately as Celcius (or whatever) and which has Celcius, Fahrenheit, and Kelvin properties that do all the conversions for you in their get and set statements?</p>\n'}, {'answer_id': 59219, 'author': 'Tyler', 'author_id': 3561, 'author_profile': 'https://Stackoverflow.com/users/3561', 'pm_score': 1, 'selected': False, 'text': "<p>By the way, it doesn't have to be more work to implement the three-parameter version, as suggested in the question statement.</p>\n\n<p>These are all linear functions, so you can implement something like</p>\n\n<pre><code>float LinearConvert(float in, float scale, float add, bool invert);\n</code></pre>\n\n<p>where the last bool indicates if you want to do the forward transform or reverse it.</p>\n\n<p>Within your conversion technique, you can have a scale/add pair for X -> Kelvin.  When you get a request to convert format X to Y, you can first run X -> Kelvin, then Kelvin -> Y by reversing the Y -> Kelvin process (by flipping the last bool to LinearConvert).</p>\n\n<p>This technique gives you something like 4 lines of real code in your convert function, and one piece of data for every type you need to convert between.</p>\n"}, {'answer_id': 59275, 'author': 'Joel Gauvreau', 'author_id': 4789, 'author_profile': 'https://Stackoverflow.com/users/4789', 'pm_score': 1, 'selected': False, 'text': '<p>Similar to what @Rob @wcm and @David explained...  </p>\n\n<pre><code>public class Temperature\n{\n    private double celcius;\n\n    public static Temperature FromFarenheit(double farenheit)\n    {\n        return new Temperature { Farhenheit = farenheit };\n    }\n\n    public static Temperature FromCelcius(double celcius)\n    {\n        return new Temperature { Celcius = celcius };\n    }\n\n    public static Temperature FromKelvin(double kelvin)\n    {\n        return new Temperature { Kelvin = kelvin };\n    }\n\n    private double kelvinToCelcius(double kelvin)\n    {\n        return 1; // insert formula here\n    }\n\n    private double celciusToKelvin(double celcius)\n    {\n        return 1; // insert formula here\n    }\n\n    private double farhenheitToCelcius(double farhenheit)\n    {\n        return 1; // insert formula here\n    }\n\n    private double celciusToFarenheit(double kelvin)\n    {\n        return 1; // insert formula here\n    }\n\n    public double Kelvin\n    {\n        get { return celciusToKelvin(celcius); }\n        set { celcius = kelvinToCelcius(value); }\n    }\n\n    public double Celcius\n    {\n        get { return celcius; }\n        set { celcius = value; }\n    }\n\n    public double Farhenheit\n    {\n        get { return celciusToFarenheit(celcius); }\n        set { celcius = farhenheitToCelcius(value); }\n    }\n}\n</code></pre>\n'}, {'answer_id': 59536, 'author': 'Jon Ericson', 'author_id': 1438, 'author_profile': 'https://Stackoverflow.com/users/1438', 'pm_score': 1, 'selected': False, 'text': '<p>I think I\'d go whole hog one direction or another.  You could write a mini-language that does any sort of conversion like <strong>units</strong> does:</p>\n\n<pre><code>$ units \'tempF(-40)\' tempC\n    -40\n</code></pre>\n\n<p>Or use individual functions like the recent <a href="http://search.cpan.org/~mopy/Convert-Temperature-0.03/" rel="nofollow noreferrer">Convert::Temperature</a> Perl module does:</p>\n\n<pre><code>use Convert::Temperature;\n\nmy $c = new Convert::Temperature();\n\nmy $res = $c-&gt;from_fahr_to_cel(\'59\');\n</code></pre>\n\n<p>But that brings up an important point---does the language you are using already have conversion functions?  If so, what coding convention do they use?  So if the language is C, it would be best to follow the example of the atoi and strtod library functions (untested):</p>\n\n<pre><code>double fahrtocel(double tempF){\n    return ((tempF-32)*(5/9));\n}\n\ndouble celtofahr(double tempC){\n    return ((9/5)*tempC + 32);\n}\n</code></pre>\n\n<hr>\n\n<p>In writing this post, I ran across a <a href="http://www.leancrew.com/all-this/2008/04/emacs-lisp-as-a-scripting-language/" rel="nofollow noreferrer">very interesting post</a> on using emacs to convert dates.  The take-away for this topic is that it uses the one function-per-conversion style.  Also, conversions can be very obscure.  I tend to do date calculations using SQL because it seems unlikely there are many bugs in that code.  In the future, I\'m going to look into using emacs.</p>\n'}, {'answer_id': 60250, 'author': 'Scott', 'author_id': 6126, 'author_profile': 'https://Stackoverflow.com/users/6126', 'pm_score': 0, 'selected': False, 'text': "<p>I wish there was some way to accept multiple answers. Based on everyone's recommendations, I think I will stick with the multiple parameters, changing the strings to enums/constants, and moving the value to be converted to the first position in the parameter list. Inside the function, I'll use Kelvin as a common middle ground.</p>\n\n<p>Previously I had written individual functions for each conversion and the overall convertTemperature() function was merely a wrapper with nested switch statements. I'm writing in both classic ASP and PHP, but I wanted to leave the question open to any language.</p>\n"}, {'answer_id': 4451615, 'author': 'Alix Axel', 'author_id': 89771, 'author_profile': 'https://Stackoverflow.com/users/89771', 'pm_score': 1, 'selected': False, 'text': "<p>Here is my take on this (using PHP):</p>\n\n<pre><code>function Temperature($value, $input, $output)\n{\n    $value = floatval($value);\n\n    if (isset($input, $output) === true)\n    {\n        switch ($input)\n        {\n            case 'K': $value = $value - 273.15; break; // Kelvin\n            case 'F': $value = ($value - 32) * (5 / 9); break; // Fahrenheit\n            case 'R': $value = ($value - 491.67) * (5 / 9); break; // Rankine\n        }\n\n        switch ($output)\n        {\n            case 'K': $value = $value + 273.15; break; // Kelvin\n            case 'F': $value = $value * (9 / 5) + 32; break; // Fahrenheit\n            case 'R': $value = ($value + 273.15) * (9 / 5); break; // Rankine\n        }\n    }\n\n    return $value;\n}\n</code></pre>\n\n<p>Basically the <code>$input</code> value is converted to the standard Celsius scale and then converted back again to the <code>$output</code> scale - one function to rule them all. =)</p>\n"}]
['https://Stackoverflow.com/questions/59102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6126/']