Given that I'd like to do the following calculation:
total = subtotal - discount
Because discount
might be greater than subtotal
, there is code like the following:
class Calculator
def initialize(subtotal: subtotal, discount: discount)
@subtotal = subtotal
@discount = discount
end
def total
[subtotal - discount, 0].max
end
private
def subtotal
@subtotal
end
def discount
@discount
end
end
When seeing the [subtotal - discount, 0].max
part or any similar code, I often have to pause and think.
Are there more elegant ways to handle this kind of calculation?