Created
April 19, 2010 07:56
-
-
Save davetron5000/370828 to your computer and use it in GitHub Desktop.
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
public class Foo { | |
public String theCurrentWay(SomeData data) { | |
if (data.getFoo() != null) { | |
if (data.getFoo().getBar() != null) { | |
if (data.getBlah() != null) { | |
return data.getFoo().getBar().getBlah().toString(); | |
} | |
} | |
} | |
return null; | |
} | |
public String aBetterWay(SomeData data) { | |
safeNull { | |
// if any of these returns null, just return null | |
return data.getFoo().getBar().getBlah().toString(); | |
} | |
} | |
public String anotherBetterWay(SomeData data) { | |
safeNull("") { | |
// if any of these returns null, just return empty string | |
return data.getFoo().getBar().getBlah().toString(); | |
} | |
} | |
} |
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
object NullSafety { | |
def safeOption[A](code: => A):Option[A] = safeOption(None)(code) | |
def safeOption[A](value: Option[A])(code: => A):Option[A] = { | |
try { | |
val result = code | |
Some(result) | |
} | |
catch { | |
case npe:NullPointerException => value | |
} | |
} | |
def safeNull[A](code: => A):A = safeNull(null)(code) | |
def safeNull[A](value:A)(code: => A):A = { | |
try { | |
code | |
} | |
catch { | |
case npe:NullPointerException => value | |
} | |
} | |
} | |
class Foo { | |
import NullSafety._ | |
def doit(DataStructure data) { | |
safeNull { | |
data.foo.bar.blah.toString | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment