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?

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
 

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

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
 

Ä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

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
 

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

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 Challengeshemanthkumar470700
 
Power point presentation on enterprise performance management
Power point presentation on enterprise performance managementPower point presentation on enterprise performance management
Power point presentation on enterprise performance managementVaishnaviGunji
 
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 PotentialFalcon investment
 
Pre Engineered Building Manufacturers Hyderabad.pptx
Pre Engineered  Building Manufacturers Hyderabad.pptxPre Engineered  Building Manufacturers Hyderabad.pptx
Pre Engineered Building Manufacturers Hyderabad.pptxRoofing Contractor
 
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.pdfAdmir Softic
 
Falcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial WingsFalcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial WingsFalcon Invoice Discounting
 
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 PROVIDINGpr788182
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptxnandhinijagan9867
 
Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel
 
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Falcon Invoice Discounting
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...daisycvs
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...ssuserf63bd7
 
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.pdfwill854175
 
Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon investment
 
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 Timegargpaaro
 
Rice Manufacturers in India | Shree Krishna Exports
Rice Manufacturers in India | Shree Krishna ExportsRice Manufacturers in India | Shree Krishna Exports
Rice Manufacturers in India | Shree Krishna ExportsShree Krishna Exports
 
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 Omaninstagramfab782445
 
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 investorsFalcon Invoice Discounting
 

Kürzlich hochgeladen (20)

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
 
Power point presentation on enterprise performance management
Power point presentation on enterprise performance managementPower point presentation on enterprise performance management
Power point presentation on enterprise performance management
 
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
 
Pre Engineered Building Manufacturers Hyderabad.pptx
Pre Engineered  Building Manufacturers Hyderabad.pptxPre Engineered  Building Manufacturers Hyderabad.pptx
Pre Engineered Building Manufacturers Hyderabad.pptx
 
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
 
Falcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial WingsFalcon Invoice Discounting: Tailored Financial Wings
Falcon Invoice Discounting: Tailored Financial Wings
 
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
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 
Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024
 
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
 
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
Quick Doctor In Kuwait +2773`7758`557 Kuwait Doha Qatar Dubai Abu Dhabi Sharj...
 
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
Horngren’s Cost Accounting A Managerial Emphasis, Canadian 9th edition soluti...
 
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
 
Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business Growth
 
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
 
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
 
Rice Manufacturers in India | Shree Krishna Exports
Rice Manufacturers in India | Shree Krishna ExportsRice Manufacturers in India | Shree Krishna Exports
Rice Manufacturers in India | Shree Krishna Exports
 
HomeRoots Pitch Deck | Investor Insights | April 2024
HomeRoots Pitch Deck | Investor Insights | April 2024HomeRoots Pitch Deck | Investor Insights | April 2024
HomeRoots Pitch Deck | Investor Insights | April 2024
 
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
 
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
 

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