0
\$\begingroup\$

for some fun, I decided to start working on something that let me work with Money calculations. I realise there are libraries out there like Joda Money, but I'm doing this mainly for fun.

I was hoping to get a review on the way I've started to construct the library.

GitHub

private def calculate(that: Money)(f: (BigDecimal, BigDecimal) => BigDecimal): Either[String, Money] = (this.currency, that.currency) match {
case (c, c1) if c == c1 => new Right(this.copy(this.currency, f(this.amount, that.amount)))
case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}

private def compare(that: Money)(f: (BigDecimal, BigDecimal) => Boolean): Either[String, Boolean] = (this.currency, that.currency) match {
    case (c, c1) if c == c1 => new Right(this.amount > that.amount)
    case _ => new Left(Money.COMPARE_ERROR_MESSAGE)
}

These two methods are incredibly similar except for the return type. Could someone suggest a way to improve this?

\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

First thoughts:

  • If an operation can fail, it is generally good practise to make this explicit in the API by returning a Try instead of an Either.
  • The duplicate code seems to stem from the fact that Money operations are only valid on Currencies of the same type. Scala gives you the power to have this check at compile time.

Example Code:

object Money {
  sealed trait Currency
  case object GBP extends Currency
}
case class Money[T <: Money.Currency](amount: BigDecimal) {
  private def calculate(that: Money[T])(f: (BigDecimal, BigDecimal) => BigDecimal): Money[T] = {
    copy(amount = f(this.amount, that.amount))
  }
  private def compare(that: Money[T])(f: (BigDecimal, BigDecimal) => Boolean): Boolean = {
    this.amount > that.amount
  }
}
\$\endgroup\$
2
  • \$\begingroup\$ Thank you. Are there any examples in libraries or anything that prefer returning try over either? \$\endgroup\$
    – user109692
    Oct 27, 2016 at 12:05
  • \$\begingroup\$ This blog post gives a good overview of exception handling with Scala: danielwestheide.com/blog/2012/12/26/… \$\endgroup\$ Nov 10, 2016 at 17:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.