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

Borderless Access - Global Panel book-unlock 2024
Borderless Access - Global Panel book-unlock 2024Borderless Access - Global Panel book-unlock 2024
Borderless Access - Global Panel book-unlock 2024Borderless Access
 
Introduction to The overview of GAAP LO 1-5.pptx
Introduction to The overview of GAAP LO 1-5.pptxIntroduction to The overview of GAAP LO 1-5.pptx
Introduction to The overview of GAAP LO 1-5.pptxJemalSeid25
 
Upgrade Your Banking Experience with Advanced Core Banking Applications
Upgrade Your Banking Experience with Advanced Core Banking ApplicationsUpgrade Your Banking Experience with Advanced Core Banking Applications
Upgrade Your Banking Experience with Advanced Core Banking ApplicationsIntellect Design Arena Ltd
 
Project Brief & Information Architecture Report
Project Brief & Information Architecture ReportProject Brief & Information Architecture Report
Project Brief & Information Architecture Reportamberjiles31
 
Building Your Personal Brand on LinkedIn - Expert Planet- 2024
 Building Your Personal Brand on LinkedIn - Expert Planet-  2024 Building Your Personal Brand on LinkedIn - Expert Planet-  2024
Building Your Personal Brand on LinkedIn - Expert Planet- 2024Stephan Koning
 
NewBase 25 March 2024 Energy News issue - 1710 by Khaled Al Awadi_compress...
NewBase  25 March  2024  Energy News issue - 1710 by Khaled Al Awadi_compress...NewBase  25 March  2024  Energy News issue - 1710 by Khaled Al Awadi_compress...
NewBase 25 March 2024 Energy News issue - 1710 by Khaled Al Awadi_compress...Khaled Al Awadi
 
The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...
The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...
The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...Brian Solis
 
Intellectual Property Licensing Examples
Intellectual Property Licensing ExamplesIntellectual Property Licensing Examples
Intellectual Property Licensing Examplesamberjiles31
 
PDT 88 - 4 million seed - Seed - Protecto.pdf
PDT 88 - 4 million seed - Seed - Protecto.pdfPDT 88 - 4 million seed - Seed - Protecto.pdf
PDT 88 - 4 million seed - Seed - Protecto.pdfHajeJanKamps
 
TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...
TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...
TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...TalentView
 
NASA CoCEI Scaling Strategy - November 2023
NASA CoCEI Scaling Strategy - November 2023NASA CoCEI Scaling Strategy - November 2023
NASA CoCEI Scaling Strategy - November 2023Steve Rader
 
BCE24 | Virtual Brand Ambassadors: Making Brands Personal - John Meulemans
BCE24 | Virtual Brand Ambassadors: Making Brands Personal - John MeulemansBCE24 | Virtual Brand Ambassadors: Making Brands Personal - John Meulemans
BCE24 | Virtual Brand Ambassadors: Making Brands Personal - John MeulemansBBPMedia1
 
Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)
Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)
Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)tazeenaila12
 
MC Heights construction company in Jhang
MC Heights construction company in JhangMC Heights construction company in Jhang
MC Heights construction company in Jhangmcgroupjeya
 
Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...
Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...
Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...IMARC Group
 
UNLEASHING THE POWER OF PROGRAMMATIC ADVERTISING
UNLEASHING THE POWER OF PROGRAMMATIC ADVERTISINGUNLEASHING THE POWER OF PROGRAMMATIC ADVERTISING
UNLEASHING THE POWER OF PROGRAMMATIC ADVERTISINGlokeshwarmaha
 
The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003
The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003
The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003believeminhh
 
Cracking the ‘Business Process Outsourcing’ Code Main.pptx
Cracking the ‘Business Process Outsourcing’ Code Main.pptxCracking the ‘Business Process Outsourcing’ Code Main.pptx
Cracking the ‘Business Process Outsourcing’ Code Main.pptxWorkforce Group
 

Último (20)

Borderless Access - Global Panel book-unlock 2024
Borderless Access - Global Panel book-unlock 2024Borderless Access - Global Panel book-unlock 2024
Borderless Access - Global Panel book-unlock 2024
 
Introduction to The overview of GAAP LO 1-5.pptx
Introduction to The overview of GAAP LO 1-5.pptxIntroduction to The overview of GAAP LO 1-5.pptx
Introduction to The overview of GAAP LO 1-5.pptx
 
Upgrade Your Banking Experience with Advanced Core Banking Applications
Upgrade Your Banking Experience with Advanced Core Banking ApplicationsUpgrade Your Banking Experience with Advanced Core Banking Applications
Upgrade Your Banking Experience with Advanced Core Banking Applications
 
Project Brief & Information Architecture Report
Project Brief & Information Architecture ReportProject Brief & Information Architecture Report
Project Brief & Information Architecture Report
 
Building Your Personal Brand on LinkedIn - Expert Planet- 2024
 Building Your Personal Brand on LinkedIn - Expert Planet-  2024 Building Your Personal Brand on LinkedIn - Expert Planet-  2024
Building Your Personal Brand on LinkedIn - Expert Planet- 2024
 
NewBase 25 March 2024 Energy News issue - 1710 by Khaled Al Awadi_compress...
NewBase  25 March  2024  Energy News issue - 1710 by Khaled Al Awadi_compress...NewBase  25 March  2024  Energy News issue - 1710 by Khaled Al Awadi_compress...
NewBase 25 March 2024 Energy News issue - 1710 by Khaled Al Awadi_compress...
 
Investment Opportunity for Thailand's Automotive & EV Industries
Investment Opportunity for Thailand's Automotive & EV IndustriesInvestment Opportunity for Thailand's Automotive & EV Industries
Investment Opportunity for Thailand's Automotive & EV Industries
 
The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...
The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...
The End of Business as Usual: Rewire the Way You Work to Succeed in the Consu...
 
Intellectual Property Licensing Examples
Intellectual Property Licensing ExamplesIntellectual Property Licensing Examples
Intellectual Property Licensing Examples
 
PDT 88 - 4 million seed - Seed - Protecto.pdf
PDT 88 - 4 million seed - Seed - Protecto.pdfPDT 88 - 4 million seed - Seed - Protecto.pdf
PDT 88 - 4 million seed - Seed - Protecto.pdf
 
TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...
TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...
TalentView Webinar: Empowering the Modern Workforce_ Redefininig Success from...
 
WAM Corporate Presentation Mar 25 2024.pdf
WAM Corporate Presentation Mar 25 2024.pdfWAM Corporate Presentation Mar 25 2024.pdf
WAM Corporate Presentation Mar 25 2024.pdf
 
NASA CoCEI Scaling Strategy - November 2023
NASA CoCEI Scaling Strategy - November 2023NASA CoCEI Scaling Strategy - November 2023
NASA CoCEI Scaling Strategy - November 2023
 
BCE24 | Virtual Brand Ambassadors: Making Brands Personal - John Meulemans
BCE24 | Virtual Brand Ambassadors: Making Brands Personal - John MeulemansBCE24 | Virtual Brand Ambassadors: Making Brands Personal - John Meulemans
BCE24 | Virtual Brand Ambassadors: Making Brands Personal - John Meulemans
 
Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)
Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)
Harvard Business Review.pptx | Navigating Labor Unrest (March-April 2024)
 
MC Heights construction company in Jhang
MC Heights construction company in JhangMC Heights construction company in Jhang
MC Heights construction company in Jhang
 
Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...
Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...
Boat Trailers Market PPT: Growth, Outlook, Demand, Keyplayer Analysis and Opp...
 
UNLEASHING THE POWER OF PROGRAMMATIC ADVERTISING
UNLEASHING THE POWER OF PROGRAMMATIC ADVERTISINGUNLEASHING THE POWER OF PROGRAMMATIC ADVERTISING
UNLEASHING THE POWER OF PROGRAMMATIC ADVERTISING
 
The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003
The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003
The Vietnam Believer Newsletter_MARCH 25, 2024_EN_Vol. 003
 
Cracking the ‘Business Process Outsourcing’ Code Main.pptx
Cracking the ‘Business Process Outsourcing’ Code Main.pptxCracking the ‘Business Process Outsourcing’ Code Main.pptx
Cracking the ‘Business Process Outsourcing’ Code Main.pptx
 

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