Hacker News new | past | comments | ask | show | jobs | submit login

In Scala, you're encouraged to write more bulletproof code by avoiding exceptions at all time, simply because it's easier to realize that (in your case) getSomeRiskyNumber returns an option instead of an integer.

  getSomeRiskyNumber map {
    case Some(i) => Map("risk" -> i)
    case None => Map("error" -> "Error retrieving number.")
  } map { response =>
    Json.toJson(response) 
  }
Reading this code you know you're always going to generate a json response to the user, and depending upon what getSomeRiskyNumber() returns, the json response will either look like { "risk": 23 } or { "error": "Error retrieving number." }. No exceptions needed.



This is something that can be paralleled easily with @Nullable. Your IDE will even tell you, before compiling, that you should expect a null case.

Also, currently, Java doesn't have a match {} expression that works with Some() and None. I belive that would completely change my opinion and the name of the game.


The match is just my personal preference to deal with option types, because I personally think it's cleaner to read. This reduces the number of flatMap chains in my code, but again, personal preference.

  Option(JavaClassFactory.staticMethodThatCanReturnNull()).map(i => i + 1).getOrElse(0)
This is a very readable function, imo, and is how 99% of Scala programmers deal with legacy Java libraries. Scala even has the Try() object, where you can do something like this:

  Try(OldJavaClass.methodThatThrowsExceptions()).toOption.map(i => i + 1).getOrElse(0)
It makes creating service-layer code so much simpler because you aren't caught in that rut of "well now I have to deal with this exception at the controller level". You can head off all that garbage very quickly. I suspect that a lot of Java Optional coders will start acting like this.


But then you will never know in your code if there was an error. What if you want to send an other HTTP response in case of an error?

With an exception you can still generate a json response, but also handle errors in the way you like.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: