HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Preventing Division by Zero

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
preventingzerodivision

Problem

numerator: Value being divided.

denominator: Divisor value.

method so far:

def calc_percentage(numerator, denominator)
  ((numerator/ (denominator.to_f.nonzero? || 1 )) * 100)
end


What 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 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     
end


This 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     
end

Context

StackExchange Code Review Q#25001, answer score: 3

Revisions (0)

No revisions yet.