Personally, I think the else
s are unnecessary. Since this question is tagged as [language-agnostic]
, I'm going to provide a couple of examples of how I would write it:
def temperature_message(temp)
return 'Freezing' if temp < 32
return 'Brr' if temp < 60
return 'Comfortable' if temp < 80
'Too hot'
end
This is typical guard clause style, which both I personally and the Ruby community in general use quite often.
def temperature_message(temp)
case
when temp < 32
'Freezing'
when temp < 60
'Brr'
when temp < 80
'Comfortable'
else
'Too hot'
end
end
This is a typical switch
as you would find it in some less powerful languages. This is probably one that I would not use, I would refactor it like this:
def temperature_message(temp)
case temp
when (-1.0/0.0)...32
'Freezing'
when 32...60
'Brr'
when 60...80
'Comfortable'
else
'Too hot'
end
end
Although I must admit I still find the first one easiest to read.
Since this is basically a mapping table, I would try to format it as such, so that everybody who reads the code, immediately sees the "table-ness":
def temperature_message(temp)
case temp
when (-1.0/0.0)...32 then 'Freezing'
when 32...60 then 'Brr'
when 60...80 then 'Comfortable'
else 'Too hot'
end
end
This also applies to your original Java implementation:
public String getTemperatureMessage(double temp) {
if(temp < 32) return "Freezing";
if(temp < 60) return "Brr";
if(temp < 80) return "Comfortable";
else return "Too hot";
}
Of course, since it is basically a mapping table, you might just as well implement it as a map:
def temperature_message(temp)
{
(-1.0/0.0)...32 => 'Freezing',
32...60 => 'Brr',
60...80 => 'Comfortable',
80..(1.0/0.0) => 'Too hot'
}.detect {|range, _| range.include?(temp) }.last
end