Maybe that's simple, but I'm a little confused.
I have such a Ruby code:
def my_function(found_objects)
# ...
if found_objects.second
return CoreObjectFactory.get_object(found_objects.second, found_objects.first)
else
return CoreObjectFactory.get_object(found_objects.first)
end
# ...
end
I left return
keywords for clarity, but there aren't the biggest problem.
According to Uncle Bob (edit: I'm sorry, that was not his opinion, I messed something) every function should have only one ending, so I'm trying to refactor my code. The simplest solution is this:
def my_function(found_objects)
# ...
if found_objects.second
result = CoreObjectFactory.get_object(found_objects.second, found_objects.first)
else
result = CoreObjectFactory.get_object(found_objects.first)
end
# ...
result
end
But here Rubocop tells me:
Use the return of the conditional for variable assignment and comparison. (convention:Style/ConditionalAssignment)
It seems to suggest something like this:
def my_function(found_objects)
# ...
result = if found_objects.second
CoreObjectFactory.get_object(found_objects.second, found_objects.first)
else
CoreObjectFactory.get_object(found_objects.first)
end
# ...
result
end
Although in my opinion it's really creepy. Number of spaces intending this code is odd, what makes it looking bad and harder to work with Tab (nested intendations inteds only one space by default).
But I could write the same this way:
def my_function(found_objects)
# ...
result = if found_objects.second
CoreObjectFactory.get_object(found_objects.second, found_objects.first)
else
CoreObjectFactory.get_object(found_objects.first)
end
# ...
result
end
It looks better for me, but unfortunately not for Rubocop, which has three conventions against me. Of course I can ignore it... but it still seems not perfect.
Layout/IndentationWidth:
Enabled: false
Layout/ElseAlignment:
Enabled: false
Layout/EndAlignment:
Enabled: false
I could also use a ternary operator, but Rubocop doesn't like long lines and multiline ternary opeators.
if found_objects
# ...
result = found_objects.second ?
CoreObjectFactory.get_object(found_objects.second, found_objects.first) :
CoreObjectFactory.get_object(found_objects.first)
# ...
result
end
So, is there some way to avoid all problems above?