Should my persistence class return Option or rely on exceptions?

The security level of my application is formed using the storage property and implementation class. I deviate from this problem: should methods fetchFoo(key: Key)return Option[Foo], or should they throw exceptions FooNotFoundif the key cannot be found?

To add flavor to the problem, the persistence layer β€” written in Scala β€” is called by Java code. Working with scala.Option in Java code? Hmmm.

In fact, until yesterday, the persistence layer was written in Java; I just rewrote it in scala. As a Java codebase, it relied on exceptions rather than returning zeros; but now that I am facing scala.Option, I am redefining. It seems to me that Scala is less in love with exceptions than Java.

+3
source share
3 answers

My common problem is that it depends on where the keys are coming from.

If they are entered by any user or an unreliable system, I use Optionso that I can meaningfully indicate the possibility of an unknown key and deal with it accordingly.

, ( , , , ), , , , . , - URL- , undefined, , IMO.

, , . Option None catch-all, , , . NotFound (, ), Option ( Either Scala), .

Java, Option , Scala . , Option Java . null, " ".

+4

Java Option isEmpty, isDefined get - ( Option, getOrElse, .) isDefined if , try-catch.

+2

(, ) , "" (map, flatMap, filter...) , , . , , , "", , , , .

Java , "" . "" (), , "" ( "" ), . Java.

0
source

Source: https://habr.com/ru/post/1768533/


All Articles