We need to think about the effect our choices have on the next person who touches the code. Often with a different baseline people make different changes. It's a micro-form of 'No Broken Windows'.
And that next person might be the newbie on the team that doesn't have the business domain knowledge built up over years of working for This Company. So I'll use the if statement to keep intent clear.
Or maybe it'll be someone whose primary programming language doesn't use the || operator. Or maybe, for some unknown reason, it'll be a PHB. So I'll use the if statement to keep intent clear.
"I want to set param to the object property or the default" is much clearer than "I want to check if if I have an object property and if I do then I'll set the param to the object property otherwise I'll set the param to the default"
That is just mixing in a lot of noise about how you do it instead of just what you are doing.
I'd rather add a method to Object/Nil called something like #or_else so that we could write
param = object.property.or_else(default_param)
which, though still terse, at least describes what's going on.> And suggests that this is better:
It depends in what terms are you thinking. A syntactic improvement is a also a benefit, isn't it?
param = object.property.nil? ? default_value : object.property
Verbose, although less so, but reveals intent almost perfectly. Would be better if the colon were "else" or "otherwise".The OR is not an if-then construct. If anything, the if-then construct is a specialised use of OR, given than if-then-else is literally XOR.
Both are an implementation of the interface "coalesce a value with null/0/false".
I only mention this because it points to a lack of precision in our thinking which I see time after time get in the way of using OOP/OOD effectively. Maybe that's a failing of OOP, but I think that if it were, it'd be a failing of programming in general, too.
This helps explain why I teach OOP the way I do: start by following the rules of removing duplication and improving names, which encourages the programmer to ask ever-more-interesting questions about what tools are available to help follow those rules, which encourages the programmer to learn OO theory as needed, rather than having it shoved in their face all at once. This just-in-time learning leads to longer-lasting understanding for many (most?) people.
def method (object)
param = default_param
if object.property
param = object.property
end
end
Here, its clear that param has a default right away.