I have this piece of code where I have a raise statement with a guard clause:
def validate_index index
# Change to SizeError
raise ArgumentError, "Size of index (#{index.size}) does not matches"\
"size of vector (#{size})" if size != index.size
end
On this, rubocop gives the offence:
Style/MultilineIfModifier: Favor a normal if-statement over a modifier clause in a multiline statement.
I modified my code to this to normal if else case as this:
def validate_index index
# Change to SizeError
if size != index.size
raise ArgumentError, "Size of index (#{index.size}) does not matches"\
"size of vector (#{size})"
end
end
But now it gives this offence:
Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.
What to do in such case? Both are raising errors. Any other alternative?
Rubocop wants you to write it like this:
def validate_index index
# Change to SizeError
return if size == index.size
raise ArgumentError, "Size of index (#{index.size}) does not matches"\
"size of vector (#{size})"
end
It is up to you if you want to go that route. Either way, Rubocop is also recommending:
def validate_index(index)
If you go your original route and ignore Rubocop, you should also really consider changing your if !=
to an unless
:
unless size == index.size
Give this a try:
This will reduce the line length while raising the argument error
def validate_index index
# Change to SizeError
error_message =
"Size of index (#{index.size}) does not matches size of vector (#{size})"
raise ArgumentError, error_message if size != index.size
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With