given i'd following calculation:
total = subtotal - discount because discount might greater subtotal, there code 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 [subtotal - discount, 0].max part or similar code, have pause , think.
are there more elegant ways handle kind of calculation?
thinking can extend numeric class?
class numeric def non_negative self > 0 ? self : 0 end end class calculator def initialize(subtotal: subtotal, discount: discount) @subtotal = subtotal @discount = discount end def total (@subtotal - @discount).non_negative end end
Comments
Post a Comment