Last active
December 16, 2015 17:49
-
-
Save gideondk/5472955 to your computer and use it in GitHub Desktop.
Why Options suck less... Ref: https://twitter.com/gideondk/status/328124728730611714
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Null based */ | |
def fetchUser(userId: String): User = db.user.fetch(userId) | |
def fetchOrganization(organizationId: String): Organization = db.organization.fetch(organizationId) | |
def fetchCase(caseId: String): Case = db.case.fetch(caseId) | |
def fetchCasesForUser(userId: String): List[Case] = { | |
val user = fetchUser(userId) | |
if (user != null) { | |
val organization = fetchOrganization(user) | |
if (organization != null) { | |
organization.caseIds.map(x => fetchCase(x)).filter(_ != null) | |
} else List[Case]() | |
} else List[Case]() | |
} | |
/* Option based */ | |
def fetchUser(userId: String): Option[User] = db.user.fetch(userId) | |
def fetchOrganization(organizationId: String): Option[Organization] = db.organization.fetch(organizationId) | |
def fetchCase(caseId: String): Option[Case] = db.case.fetch(caseId) | |
def fetchCasesForUser(userId: String): Option[List[Case]] = for { | |
user <- fetchUser(userId) | |
org <- fetchOrganization(user.organizationId) | |
} yield org.caseIds.flatMap(x => fetchCase(x)) |
You're right, leaving the explicit function notations for the non-Scala programmers among us...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
yield
part can be expressed more succinctly asorg.caseIds flatMap fetchCase
. Also, the method returnsOption[List[Case]]
.Good example, though.