patternrubyMinor
Preventing Division by Zero
Viewed 0 times
preventingzerodivision
Problem
numerator: Value being divided.
denominator: Divisor value.
method so far:
What are the bad practices you see in the code above? How can I improve it or write it in a better way ?
denominator: Divisor value.
method so far:
def calc_percentage(numerator, denominator)
((numerator/ (denominator.to_f.nonzero? || 1 )) * 100)
endWhat are the bad practices you see in the code above? How can I improve it or write it in a better way ?
Solution
Well to me the bad thing is that the function produces an unexpected behavior.
You try to divide by
What I would do is throw an Argument Error Exception (or what ever other exception that you think is appropriate).
This way it produces something that is logic and consistent.
You try to divide by
0, it divides by 1. Huh?What I would do is throw an Argument Error Exception (or what ever other exception that you think is appropriate).
def calc_percentage(numerator, denominator)
if denominator.to_f.nonzero
then (numerator/ denominator.to_f) * 100
else raise ArgumentError, "Denominator can not be 0.", caller
end
endThis way it produces something that is logic and consistent.
Code Snippets
def calc_percentage(numerator, denominator)
if denominator.to_f.nonzero
then (numerator/ denominator.to_f) * 100
else raise ArgumentError, "Denominator can not be 0.", caller
end
endContext
StackExchange Code Review Q#25001, answer score: 3
Revisions (0)
No revisions yet.