3 ms·
This is a terrible example of IF-less programming. The conditional is still here, it is just implied. IF: def method (object) if object.property
by killahpriest 14y ago
This is a terrible example of IF-less programming. The conditional is still here, it is just implied.
IF:
def method (object)
if object.property
param = object.property
else
param = default_param
end
end
Claimed to be IF-less:
def method (object)
param = object.property || default_param
end
It may be easier to read, but in the end you are still writing an IF statement.
- dsego 14y agoIt's not only easier to read, but it clearly shows the intent, that it is only an assignment. It's faster to comprehend too, you don't even have to look at the right hand side if you're not interested. The first example obfuscates the intent a bit. Also, in other languages, you'd have to declare the variable first and that's even more lines of code.
- dragonwriter 14y agoIt would be just as clear in expressing that the intent is an assignment (and more clear what is being assigned, since it avoids the coalescing-OR) though less concise to leverage the fact that Ruby's "if" is an expression not a statement: <code> param = if object.property then object.property else default_param end </code> Though, actually if you want to do what the description says (use the default if the property is unassigned, represented conventionally in Ruby by the accessor returning nil) rather than what either the good or bad code does, you probably want: <code> param = if not object.property.nil? then object.property else default_param end </code> (The difference between this and the other versions shows up if the property is assigned, and its value is false.)
- killahpriest 14y agoThe code tag does nothing, do this instead: Text after a blank line that is indented by two or more spaces is reproduced verbatim. (This is intended for code.) http://news.ycombinator.com/formatdoc http://news.ycombinator.com/formatdoc