2

I'm designing a method returning and want to keep referntial transparency. So instead of returning the result and checking preconditions I return Either[Throwable, String]. It currently looks as follows:

def logName(arg: String): Either[Throwable, String] =
  if (arg.lenght < 5)
    Right(arg)
  else
    Left(new IllegalArgumentException(s"Illegal lenght"))

The thing I was confused by is that I create exception and don't throw it, but just store it inside Left object. Is that a common pattern to preserver referential transparency?

Raman Mishra
  • 2,635
  • 2
  • 15
  • 32
Some Name
  • 8,555
  • 5
  • 27
  • 77

1 Answers1

2

In short, yes.

Throwing and catching exceptions disrupts the normal flow of execution, so any function that throws an exception can't be referentially transparent. By returning the exception class instance wrapped in an instance of the declared return type, you're preserving the error state, and making the call referentially transparent too. Also, you're allowing the caller to determine what should happen subsequently.

Depending upon your requirements, and as you may already be aware, scala.util.Try is another alternative to scala.util.Either. See this answer to "What is the difference between Try and Either?" for more information on the differences between the two. If you don't care what exception arises, scala.Option is another possibility.

Mike Allen
  • 8,139
  • 2
  • 24
  • 46