SlideShare una empresa de Scribd logo
1 de 14
Descargar para leer sin conexión
Better Strategies for Null Handling in Java
Stephan Schmidt
Team manager PMI-3




Berlin, 05.08.2008
Most problematic errors in Java


      2 runtime problems in Java
       ClassCastException
         „Solved“ with Generics
       NullPointerException (NPE)
         Solution?



2
Problems with NPEs



        RunTime Exception
    –

        Point of NPE easy to find
    –

        => But not clear where the NULL value comes
          from




3
Handling of NULL Values

                                              Check after
    Check before

                                              String name = map.get(quot;Helloquot;);
    if (map.containsKey(quot;Helloquot;)) {
                                              if (name != null) {
            String name = map.get(“hallo”);
                                              ...
    } else { … }
                                              } else { … }



          Easy to forget
      –

          No support from type system
      –

          No tracking of NULL values
      –

              Can a reference be NULL ?
          •



4
Null Handling in Groovy



    def user = users[“hello”]
    def streetname = user?.address?.street


    Safe Navigation Operator ?.
       user, address can be NULL
       will simply return NULL instead of throwing an exception



5
Null types in Nice language



    Nice language NULL types

    - ?String name => possibly NULL
    - String name => not NULL

    String name = null;
    => Compiler error

6
NULL Handling with Annotations


       @NotNull, @Nullable in Java
           IDEA and others, JSR 308
           Automatic checks for NULL
           IDEA tells you when NPEs will occure
       @NotNull
       public String get(@NotNull String name) { … }


    Everything not null and @Optional for NULL better solution
7
Scala Option Class


    Option can have a value or not (think container with 0 or 1 elements).
    Subclasses are Some and None
    Must deal with None (NULL) value, cannot ignore
    Called Maybe (Just, Nothing) in Haskell



    map.get(quot;Helloquot;) match {
      case Some(name) => // do something with name
      case None    => // do nothing
    }
8
Option in Java


    Option<String> option = map.get(„hello“);
    if (option instanceof Some) {
           String name = ((Some) option).value();
           ….
    } else {
           // option is none, there is no „hello“
    }




    Explicit handling of „NULL“ value necessary
    Or:
    option.isSome() and option.value() without cast
9
For Trick for Option with Iterable


     Sometimes the none case needs no handling
     For and Iterable<T> can be used
     For automatically unwraps Option, does nothing in None case
     None returns EMPTY list, Some one element list with option value


     public class Option<T> implements Iterable<T> { … }

     for (String name: getName(“hello”)) {
            // do something with name
     }

10
Convenience methods



     Option<String> name = none();


     Option<String> name = option(dontKnow);


     Option<String> name = some(„stephan“);




11
How does this method handle
     NULL values?


     API makes the intention clear
       public Option<String> getName() {…}
       public String getName() { …}
       public void setName(Option<String> name) { … }
       public void setName(String name) { … }




12
Easy default values with orElse()



     String name = map.get(„hello“).orElse(„stephan“);




     Easy handling of default values
     Very little code compared to Check Before or
     Check After for default handling in Java



13
Questions?



www.ImmobilienScout24.de

Más contenido relacionado

La actualidad más candente

Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspectiveNorman Richards
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8JavaDayUA
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Benjamin Bock
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation streamRuslan Shevchenko
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language ComparisonRobert Bachmann
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesRay Toal
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 

La actualidad más candente (20)

Logic programming a ruby perspective
Logic programming a ruby perspectiveLogic programming a ruby perspective
Logic programming a ruby perspective
 
Clean code
Clean codeClean code
Clean code
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)Ruby Topic Maps Tutorial (2007-10-10)
Ruby Topic Maps Tutorial (2007-10-10)
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Clean code
Clean codeClean code
Clean code
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Operators
OperatorsOperators
Operators
 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax Trees
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 

Similar a Better Strategies for Null Handling in Java

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In PerlKang-min Liu
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee confIgor Anishchenko
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Lucas Witold Adamus
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)jeresig
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaJohn Leach
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlHideaki Ohno
 

Similar a Better Strategies for Null Handling in Java (20)

Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
New syntax elements of java 7
New syntax elements of java 7New syntax elements of java 7
New syntax elements of java 7
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)
 
Groovy And Grails JUG Sardegna
Groovy And Grails JUG SardegnaGroovy And Grails JUG Sardegna
Groovy And Grails JUG Sardegna
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
 

Más de Stephan Schmidt

Focus, Focus, Focus - The one thing that makes a difference
Focus, Focus, Focus - The one thing that makes a differenceFocus, Focus, Focus - The one thing that makes a difference
Focus, Focus, Focus - The one thing that makes a differenceStephan Schmidt
 
Employee Live Cycle JAX 2016
Employee Live Cycle JAX 2016Employee Live Cycle JAX 2016
Employee Live Cycle JAX 2016Stephan Schmidt
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with ReduxStephan Schmidt
 
Short Guide to Productivity
Short Guide to ProductivityShort Guide to Productivity
Short Guide to ProductivityStephan Schmidt
 
10 Years of My Scrum Experience
10 Years of My Scrum Experience10 Years of My Scrum Experience
10 Years of My Scrum ExperienceStephan Schmidt
 
What Top Management Needs to Know About IT
What Top Management Needs to Know About ITWhat Top Management Needs to Know About IT
What Top Management Needs to Know About ITStephan Schmidt
 
What managers need_to_know
What managers need_to_knowWhat managers need_to_know
What managers need_to_knowStephan Schmidt
 
What everyone should know about time to market
What everyone should know about time to marketWhat everyone should know about time to market
What everyone should know about time to marketStephan Schmidt
 
Berlin.JAR: Web future without web frameworks
Berlin.JAR: Web future without web frameworksBerlin.JAR: Web future without web frameworks
Berlin.JAR: Web future without web frameworksStephan Schmidt
 

Más de Stephan Schmidt (11)

Focus, Focus, Focus - The one thing that makes a difference
Focus, Focus, Focus - The one thing that makes a differenceFocus, Focus, Focus - The one thing that makes a difference
Focus, Focus, Focus - The one thing that makes a difference
 
Employee Live Cycle JAX 2016
Employee Live Cycle JAX 2016Employee Live Cycle JAX 2016
Employee Live Cycle JAX 2016
 
State Models for React with Redux
State Models for React with ReduxState Models for React with Redux
State Models for React with Redux
 
Short Guide to Productivity
Short Guide to ProductivityShort Guide to Productivity
Short Guide to Productivity
 
10 Years of My Scrum Experience
10 Years of My Scrum Experience10 Years of My Scrum Experience
10 Years of My Scrum Experience
 
What Top Management Needs to Know About IT
What Top Management Needs to Know About ITWhat Top Management Needs to Know About IT
What Top Management Needs to Know About IT
 
What managers need_to_know
What managers need_to_knowWhat managers need_to_know
What managers need_to_know
 
What everyone should know about time to market
What everyone should know about time to marketWhat everyone should know about time to market
What everyone should know about time to market
 
LMAX Architecture
LMAX ArchitectureLMAX Architecture
LMAX Architecture
 
Developer Testing
Developer TestingDeveloper Testing
Developer Testing
 
Berlin.JAR: Web future without web frameworks
Berlin.JAR: Web future without web frameworksBerlin.JAR: Web future without web frameworks
Berlin.JAR: Web future without web frameworks
 

Último

India Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportIndia Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportMintel Group
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCRashishs7044
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncrdollysharma2066
 
Islamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in IslamabadIslamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in IslamabadAyesha Khan
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...ictsugar
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCRashishs7044
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Kirill Klimov
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfrichard876048
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCRashishs7044
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis UsageNeil Kimberley
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessSeta Wicaksana
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?Olivia Kresic
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMVoces Mineras
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africaictsugar
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfJos Voskuil
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy Verified Accounts
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 

Último (20)

India Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportIndia Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample Report
 
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
8447779800, Low rate Call girls in Uttam Nagar Delhi NCR
 
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / NcrCall Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
Call Girls in DELHI Cantt, ( Call Me )-8377877756-Female Escort- In Delhi / Ncr
 
Islamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in IslamabadIslamabad Escorts | Call 03070433345 | Escort Service in Islamabad
Islamabad Escorts | Call 03070433345 | Escort Service in Islamabad
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR8447779800, Low rate Call girls in Rohini Delhi NCR
8447779800, Low rate Call girls in Rohini Delhi NCR
 
Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024Flow Your Strategy at Flight Levels Day 2024
Flow Your Strategy at Flight Levels Day 2024
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdf
 
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
8447779800, Low rate Call girls in Shivaji Enclave Delhi NCR
 
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCREnjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage2024 Numerator Consumer Study of Cannabis Usage
2024 Numerator Consumer Study of Cannabis Usage
 
Organizational Structure Running A Successful Business
Organizational Structure Running A Successful BusinessOrganizational Structure Running A Successful Business
Organizational Structure Running A Successful Business
 
MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?MAHA Global and IPR: Do Actions Speak Louder Than Words?
MAHA Global and IPR: Do Actions Speak Louder Than Words?
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQM
 
Kenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby AfricaKenya’s Coconut Value Chain by Gatsby Africa
Kenya’s Coconut Value Chain by Gatsby Africa
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdf
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail Accounts
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 

Better Strategies for Null Handling in Java

  • 1. Better Strategies for Null Handling in Java Stephan Schmidt Team manager PMI-3 Berlin, 05.08.2008
  • 2. Most problematic errors in Java 2 runtime problems in Java ClassCastException „Solved“ with Generics NullPointerException (NPE) Solution? 2
  • 3. Problems with NPEs RunTime Exception – Point of NPE easy to find – => But not clear where the NULL value comes from 3
  • 4. Handling of NULL Values Check after Check before String name = map.get(quot;Helloquot;); if (map.containsKey(quot;Helloquot;)) { if (name != null) { String name = map.get(“hallo”); ... } else { … } } else { … } Easy to forget – No support from type system – No tracking of NULL values – Can a reference be NULL ? • 4
  • 5. Null Handling in Groovy def user = users[“hello”] def streetname = user?.address?.street Safe Navigation Operator ?. user, address can be NULL will simply return NULL instead of throwing an exception 5
  • 6. Null types in Nice language Nice language NULL types - ?String name => possibly NULL - String name => not NULL String name = null; => Compiler error 6
  • 7. NULL Handling with Annotations @NotNull, @Nullable in Java IDEA and others, JSR 308 Automatic checks for NULL IDEA tells you when NPEs will occure @NotNull public String get(@NotNull String name) { … } Everything not null and @Optional for NULL better solution 7
  • 8. Scala Option Class Option can have a value or not (think container with 0 or 1 elements). Subclasses are Some and None Must deal with None (NULL) value, cannot ignore Called Maybe (Just, Nothing) in Haskell map.get(quot;Helloquot;) match { case Some(name) => // do something with name case None => // do nothing } 8
  • 9. Option in Java Option<String> option = map.get(„hello“); if (option instanceof Some) { String name = ((Some) option).value(); …. } else { // option is none, there is no „hello“ } Explicit handling of „NULL“ value necessary Or: option.isSome() and option.value() without cast 9
  • 10. For Trick for Option with Iterable Sometimes the none case needs no handling For and Iterable<T> can be used For automatically unwraps Option, does nothing in None case None returns EMPTY list, Some one element list with option value public class Option<T> implements Iterable<T> { … } for (String name: getName(“hello”)) { // do something with name } 10
  • 11. Convenience methods Option<String> name = none(); Option<String> name = option(dontKnow); Option<String> name = some(„stephan“); 11
  • 12. How does this method handle NULL values? API makes the intention clear public Option<String> getName() {…} public String getName() { …} public void setName(Option<String> name) { … } public void setName(String name) { … } 12
  • 13. Easy default values with orElse() String name = map.get(„hello“).orElse(„stephan“); Easy handling of default values Very little code compared to Check Before or Check After for default handling in Java 13