^Logo by Use Try or Either from Vavr.
A case where you are processing a value in Stream and you have to handle a checked exception in a lambda expression in the middle
Note: Please think that it is difficult to change the BookReader
because it is external.
A case where the runtime error is changed to RuntimeError. If you're handling errors properly within a method or in a private range, it's hard if you're throwing exceptions into the public world. Also, I'm worried that even if I don't do that now, I can casually do that.
Right. I think it's better than throwing a RuntimeError. The number of local variables has increased from 0 to 2, the amount of coding has more than doubled, and the nesting is 2 levels deeper, but if the whole team is satisfied with this, it would be good. ..
For example, Golang uses tuples (sets of multiple instances) to propagate anomalous results to the caller, but Java does not support tuples at the language specification level. You can substitute it by creating a class, but for functional programming, you can use Scala or Haskell for a better idea.
Vavr is a library that facilitates functional programming in Java.
Either
A class that takes either a Right
or Left
value. It is customary to set Right
for the normal system and Left
for the abnormal system. (pun)
I think it would be nice if you could have an enhanced image of ʻOptional. With ʻOptional
, only information about whether or not it is null
can be sent downstream of Stream, but with ʻEither`, values such as exceptions can be sent.
Try
It is a class for writing try-catch as a function type as it is. You can receive a lambda expression that can throw a checked exception and express the processing when an exception occurs in the form of lambda.
Think of this as an enhanced version of ʻOptional that contains either normal or abnormal values, just like ʻEither
.
Looking only at the atmosphere, it seems that Try is an option, but in Try, the input of abnormal processing becomes Throwable
and downcasting tends to occur, so there are cases where writing with ʻEither` is not moyamoya.
For example, I think it will look like this.
Either:
Try:
Note that Try is throws Throwable
. Downcasting is required for proper handling.
Once you start using Vavr hard, it will no longer look like Java and will be difficult to maintain, and you will start asking yourself why you are not using Scala or Haskell, so it is recommended to use it as a pinch.
Isn't it necessary to continue using Java forcibly? May be advised to the boss.
I wonder if this is about OSS ...
Recommended Posts