{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "@id": "https://www.vidyasource.com/blog/know-your-options-scala-java/",
  "url": "https://www.vidyasource.com/blog/know-your-options-scala-java/",
  "mainEntityOfPage": "https://www.vidyasource.com/blog/know-your-options-scala-java/",
  "headline": "Know Your Options",
  "description": "Null is a real pain, but functional languages like Scala can make it a lot easier.",
  "datePublished": "2014-08-04T00:00:00.000Z",
  "author": {
    "@type": "Person",
    "name": "Neil Chaudhuri",
    "jobTitle": "President",
    "url": "https://www.linkedin.com/in/neil-chaudhuri/",
    "sameAs": "https://www.linkedin.com/in/neil-chaudhuri/"
  },
  "publisher": {
    "@id": "https://www.vidyasource.com/#organization"
  },
  "image": "https://www.vidyasource.com/img/blog/options.jpeg",
  "keywords": [
    "Java",
    "Scala",
    "Ruby",
    "Programming",
    "Functional Programming"
  ],
  "articleBody": "Imagine a method in Java that retrieves an `Employee` entity from the database by the employee id. Something like this:\n\n~~~java\npublic Employee findById(String id) {\n// Try to find an Employee\n}\n~~~\n\nThat's pretty straightforward. You've probably written hundreds of methods like this one. The problem is what to do if\nthere is *no* employee with that id. Java developers usually consider two options for this scenario:\n\n* Throw a [checked exception](http://en.wikibooks.org/wiki/Java_Programming/Checked_Exceptions)\n* Return `null`\n\nSure, you could also apply the [Null Object Pattern](http://en.wikipedia.org/wiki/Null_Object_pattern#Java), but no one ever does that.\n\nThrowing a checked exception has one huge advantage. It explicitly alerts you to the possibility you won't find an employee\nwith the id, and the compiler forces you to deal with that possibility by either kicking the can down the road with a rethrow\nor by catching the exception. The problem is that using exceptions to regulate flow control is generally considered\n[a bad idea](http://stackoverflow.com/questions/729379/why-not-use-exceptions-as-regular-flow-of-control).\n\nOn the other hand, returning `null` implies using a conditional statement for flow control, which is preferred. The problem is that `null`\nis basically the worst thing ever. Even the guy who invented it\n[thinks so](http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare). For details on\nwhy `null` is basically the worst thing ever, check out what the [Google Guava](https://code.google.com/p/guava-libraries/) team\n[has to say about it](https://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained).\n\nVarious languages address the issues with `null` in different ways. Ruby, for example, has `nil`, which is a singleton\ninstance of [NilClass](http://www.ruby-doc.org/core-2.1.2/NilClass.html), which can be\n[monkey-patched](http://stackoverflow.com/questions/394144/what-does-monkey-patching-exactly-mean-in-ruby) in clever ways\nto mitigate some of those issues.\n\nA much cleaner, more sophisticated approach is to use the concept of [optional types](http://en.wikipedia.org/wiki/Option_type),\nwhich is sort of utilized in Guava and has its origins in mathematical [type theory](http://en.wikipedia.org/wiki/Type_theory)\nand functional programming languages like Haskell and Scala, where I was first introduced to the\nconcept. Since then, Scala's `Option` type has become one of my favorite features of the language.\n\nLet's go back to our original example. In Scala, it would probably look like this.\n\n~~~scala\ndef findById(id: String): Option[Employee] = {\n// Return an Employee effect\n}\n~~~\n\nCheck out that `Option[Employee]` return type. The `Option` type has a [rigorous definition](http://www.scala-lang.org/api/current/index.html#scala.Option), but as a practical matter, think of it as a one-item\ncollection. If we find an employee with the given id, the collection contains the corresponding `Employee` instance. If\nwe don't, the collection contains a singleton--similar to Ruby's `nil` and some applications of the Null Object Pattern.\n\n[Some](http://www.scala-lang.org/api/current/index.html#scala.Some) and [None](http://www.scala-lang.org/api/current/index.html#scala.None$)\nare instances of `Option`. So more precisely, when we find an employee, our method returns an instance of `Some[Employee]`.\nWhen we don't, our method returns `None`.\n\nWhat's the big deal? Two things.\n\nFirst, just like with the exception approach, we have a compile-time mandate to account for both possibilities. There is\nno chance we will be caught by surprise at runtime and slow down our development cycle. But this compile-time checking\nis accomplished with type safety rather than a problematic exception.\n\nSecond, and even better, the caller's code is really clean. You could call our method like this:\n\n~~~scala\nval employeeName = findById(\"123\")\n  .map(employee => employee.getName)\n  .filter(name => name.length != 0)\n  .getOrElse(\"Unknown\")\n~~~\n\nIf you have worked with Scala collections before, you'll notice how similar it is to use `Option`. In this case,\nif `findById` returns `Some`, the `map` call extracts the `Employee` instance “inside” the `Some`, and you can do whatever you want\nwith it. Here we get the employee's name in the `map` call and run the name through a `filter` to make\nsure it isn't blank. If it isn't, the employee's name is stored in the variable. The `getOrElse` call never happens.\n\nHowever, if `findById` returns `None`, the `map` and `filter` calls never happen, and `getOrElse` handles this alternate flow. In fact, `getOrElse`\nexecutes when *any* method along the call chain returns `None`. So if there is an employee with given id but the name is blank,\n`map` returns `Some` but `filter` returns `None`, and `getOrElse` does its thing in this case as well.\n\nAll scenarios are accounted for, and the code is elegant and pretty easy to follow if you are comfortable with actual\ncollections. You can even use [flatMap](http://alvinalexander.com/scala/collection-scala-flatmap-examples-map-flatten)\nif you have `Option`'s within `Option`'s. That's cool.\n\nHopefully now you know why I love `Option` so much. Even if you don't program in Scala, you can think differently\nabout your code no matter which language you use. For much more on `Option`, check out Daniel Westheide's\n[outstanding post](http://danielwestheide.com/blog/2012/12/19/the-neophytes-guide-to-scala-part-5-the-option-type.html)\non the topic."
}