SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
Ray Toal
 

Was ist angesagt? (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
 

Ähnlich wie Better Strategies for Null Handling in Java

Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
Kang-min Liu
 
Yapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed PerlYapcasia2011 - Hello Embed Perl
Yapcasia2011 - Hello Embed Perl
Hideaki Ohno
 

Ähnlich wie 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
 

Mehr von Stephan Schmidt

What managers need_to_know
What managers need_to_knowWhat managers need_to_know
What managers need_to_know
Stephan Schmidt
 

Mehr von 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
 

Kürzlich hochgeladen

Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
allensay1
 
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in OmanMifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
instagramfab782445
 
Mckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for ViewingMckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for Viewing
Nauman Safdar
 

Kürzlich hochgeladen (20)

Pre Engineered Building Manufacturers Hyderabad.pptx
Pre Engineered  Building Manufacturers Hyderabad.pptxPre Engineered  Building Manufacturers Hyderabad.pptx
Pre Engineered Building Manufacturers Hyderabad.pptx
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Falcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial WingsFalcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial Wings
 
PHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation FinalPHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation Final
 
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdfDr. Admir Softic_ presentation_Green Club_ENG.pdf
Dr. Admir Softic_ presentation_Green Club_ENG.pdf
 
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
Escorts in Nungambakkam Phone 8250092165 Enjoy 24/7 Escort Service Enjoy Your...
 
Over the Top (OTT) Market Size & Growth Outlook 2024-2030
Over the Top (OTT) Market Size & Growth Outlook 2024-2030Over the Top (OTT) Market Size & Growth Outlook 2024-2030
Over the Top (OTT) Market Size & Growth Outlook 2024-2030
 
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
 
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in OmanMifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
Mifepristone Available in Muscat +918761049707^^ €€ Buy Abortion Pills in Oman
 
Arti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdfArti Languages Pre Seed Teaser Deck 2024.pdf
Arti Languages Pre Seed Teaser Deck 2024.pdf
 
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAIGetting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
 
Cracking the 'Career Pathing' Slideshare
Cracking the 'Career Pathing' SlideshareCracking the 'Career Pathing' Slideshare
Cracking the 'Career Pathing' Slideshare
 
Falcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business PotentialFalcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business Potential
 
Mckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for ViewingMckinsey foundation level Handbook for Viewing
Mckinsey foundation level Handbook for Viewing
 
Falcon Invoice Discounting: Aviate Your Cash Flow Challenges
Falcon Invoice Discounting: Aviate Your Cash Flow ChallengesFalcon Invoice Discounting: Aviate Your Cash Flow Challenges
Falcon Invoice Discounting: Aviate Your Cash Flow Challenges
 
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
Lundin Gold - Q1 2024 Conference Call Presentation (Revised)
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investors
 
Call 7737669865 Vadodara Call Girls Service at your Door Step Available All Time
Call 7737669865 Vadodara Call Girls Service at your Door Step Available All TimeCall 7737669865 Vadodara Call Girls Service at your Door Step Available All Time
Call 7737669865 Vadodara Call Girls Service at your Door Step Available All Time
 
Famous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st CenturyFamous Olympic Siblings from the 21st Century
Famous Olympic Siblings from the 21st Century
 

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