Last active
December 7, 2016 15:38
-
-
Save gaplo917/5dc037bedea39a348854ae59ba89c063 to your computer and use it in GitHub Desktop.
Java Null Risk Example
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
// Java null risk workaround example | |
// Kotlin null safe example https://gist.github.com/gaplo917/77d7ee9f48ed20f4a60bc20a1b39a2e6 | |
import org.jetbrains.annotations.NotNull; | |
import org.jetbrains.annotations.Nullable; | |
import java.util.Optional; | |
import static java.lang.System.*; | |
class NullRisk { | |
// Bad code in Java | |
public String doRiskyThing(String str){ | |
return str.toLowerCase(); | |
} | |
// Human error by typing wrong annotation, should be @NotNull | |
public String doMissLeadingThing(@Nullable String str){ | |
return str.toLowerCase(); // IDE warning | |
} | |
// possible work around, IDE will show warning if the input is null | |
// but it is safe to compile | |
@NotNull | |
public String doSafeThing(@NotNull String str){ | |
return str.toLowerCase(); | |
} | |
// possible work around, but using Optional in java is pain and not handy as Kotlin/Scala | |
public Optional<String> doOptionalThing(@Nullable String strOpt){ | |
return Optional.ofNullable(strOpt).map(String::toLowerCase); | |
} | |
{ | |
// compile OK! throw NullPointerException in run-time | |
out.println(doRiskyThing(null)); | |
// compile OK! IDE warning, throw NullPointerException in run-time | |
out.println(doSafeThing(null)); | |
// compile OK! throw NullPointerException in run-time | |
out.println(doMissLeadingThing(null)); | |
// compile OK! | |
out.println(doOptionalThing(null)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment