SlideShare a Scribd company logo
1 of 25
Java 8
Optionals are not optionals
What’s wrong with null?
What’s wrong with null?
• Null references were introduced in 1965 byTony Hoare while designingALGOLW.
• He thought it was the most convenient way to model the absense of a value.
• Many programming languages followed this approach.
• After many years he sees his decisión as “my billion-dollar mistake”.
What’s wrong with null?
A little example
What’s wrong with null?
A little example
What’s wrong with null?
A little example
What’s wrong with null?
What’s wrong with null?
• NullPointerException is one of the most common exceptions thrown in Java.
• It worsens readability.
• It’s the only thing in Java that makes pointers are not hidden.
Optional to the rescue
Optional to the rescue
What is an Optional?
• A class that encapsulates an optional value.
• When the value is present, the Optional just wraps it.
• If the value is not present, the OptionalWill be a special singleton instance representing an empty
Optional.
Optionals to the rescue
A little example
Optionals to the rescue
A little example
Optionals to the rescue
A little example
Optionals to the rescue
A little example
Optionals to the rescue
A little example
Creating Optionals
Creating Optionals
Empty Optional
Creating Optionals
An Optional from a non-null value
Creating Optionals
Optional from null
Transforming Optionals
Transforming Optionals
Extracting information
Transforming Optionals
Chaining Optionals
Transforming Optionals
Unwrapping Optionals
Transforming Optionals
Rejecting Optional values
The End

More Related Content

What's hot

The Difference Between TypeScript V/S JavaScript
The Difference Between TypeScript V/S JavaScriptThe Difference Between TypeScript V/S JavaScript
The Difference Between TypeScript V/S JavaScriptInnvonixTechSolution
 
Difference between is and as operators in c#
Difference between is and as operators in c#Difference between is and as operators in c#
Difference between is and as operators in c#Umar Ali
 
Java Arrays
Java ArraysJava Arrays
Java ArraysOXUS 20
 
LinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | EdurekaLinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | EdurekaEdureka!
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptionsİbrahim Kürce
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 
5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)Amit Gupta
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptionsmyrajendra
 

What's hot (10)

The Difference Between TypeScript V/S JavaScript
The Difference Between TypeScript V/S JavaScriptThe Difference Between TypeScript V/S JavaScript
The Difference Between TypeScript V/S JavaScript
 
Difference between is and as operators in c#
Difference between is and as operators in c#Difference between is and as operators in c#
Difference between is and as operators in c#
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
LinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | EdurekaLinkedList vs ArrayList in Java | Edureka
LinkedList vs ArrayList in Java | Edureka
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)5 easy steps to understanding json web tokens (jwt)
5 easy steps to understanding json web tokens (jwt)
 
Code Review
Code ReviewCode Review
Code Review
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
07 java variables
07   java variables07   java variables
07 java variables
 

Recently uploaded

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 

Recently uploaded (20)

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 

Java 8 - Optionals

Editor's Notes

  1. Fin: Para que veamos a qué se refería, veamos un ejemplo
  2. Imaginad que tenéis esta relación entre estas tres clases. Un cliente tiene una cuenta y cada cuenta está asociada a un método de pago. Ahora vuestro cliente os pide que creéis un método que obtenga el nombre del método de pago asociado a un cliente.
  3. La solución más simple sería la siguiente, accediendo a cada atributo de forma escalonada. ¿Pero qué pasaría si client, getAccount() o getPaymentMethod() fuera nulo? FIN: Una forma de solucionar este problema sería comprobar que cada atributo fuera distinto a null antes de acceder a ellos.
  4. Como vemos, en este caso por cada “duda” que tenemos, realizamos una comprobación, comprometiendo la legibilidad y complejidad ciclomática. Fin: Otra posibilidad que reduciría la complejidad ciclomática sería devolver el valor por defecto cada vez que nos encontremos con un posible null.
  5. En este caso, aunque nos hemos librado de los condicionales anidados, hemos aumentado a 4 los puntos de retorno del método. El método sigue siendo feo. FIN: Como vemos, el uso de la referencia nula nos da ciertos quebraderos de cabeza.
  6. ANTES DEL MEME: Por todo esto podemos decir que, uno trata con referencias nulas así como así.
  7. Por suerte Java 8 nos ha dado una forma para mitigar el daño de la referencia nula: Los Optionals.
  8. Un Optional en Java no es más que una clase que encapsula un valor opcional. Si el valor está presente, simplemente lo contiene. Si el valor en cambio no está presente, contendrá una instancia especial que representa a un valor vacío. FIN: Y vosotros os preguntaréis ¿Cuál es la diferencia a usar null? Sigamos con el ejemplo anterior.
  9. Partamos del ejemplo anterior. Un cliente con una cuenta y un método de pago. ¿Qué sucedería si modificamos los getters de los atributos que pueden ser nulos y hacemos que devuelvan un Optional? Tendríamos un modelo como el siguiente. FIN: Veamos como quedaría el código.
  10. ¿Os acordáis de este método tan feo? Haciendo uso de Optionals podremos pasar a esto. ¿Qué está sucediendo? (Explicar) Si no habéis trabajado con Optionals, es normal que os sintáis así (Imagen de abuela), pero no os preocupéis, ahora veremos más en profundidad lo que ha sucedido.
  11. ¿Os acordáis de este método tan feo? Haciendo uso de Optionals podremos pasar a esto. ¿Qué está sucediendo? (Explicar) Si no habéis trabajado con Optionals, es normal que os sintáis así (Imagen de abuela), pero no os preocupéis, ahora veremos más en profundidad lo que ha sucedido.
  12. El primer paso para trabajar con Optionals es saber como crearlos.
  13. Lo más simple es crear un Optional vacío.
  14. Si quisiérais crear un Optional a partir de un valor que no debe ser nulo. ¿Qué pasaría myInteger fuera null? NullPointerException ¿Qué sentido tiene?¿No nos habíamos liberado de esta lacra? Nos sirve para cuando necesitamos un objeto Optional a partir de un valor que no puede ser nulo.
  15. Finalmente podremos crear Optionals a partir de valores que pueden o no ser nulos, en cuyo caso el valor del optional será Optional.empty().
  16. El siguiente paso es transformar Optionals.
  17. Si quisiéramos obtener un atributo o llamada a un método de un Optional, lo podríamos hacer mediante el método ”map”. En este ejemplo estamos extrayendo el nombre del método de pago. Ya que estamos extrayendo un valor de un Optional, el resultado de esta operación es otro Optional. FIN: Otra forma de modificar un Optional es transformarlo en otro Optional. Volvamos un momento al primer método con optionals que hemos visto.
  18. Como vemos, tenemos dos llamadas a flatMap(). Con esta llamada lo que hacemos es transformar el Optional en otro Optional, en este caso específico, en el de los atributos que contiene. ¿Por qué no usar map()? Porque map() devuelve un Optional del objeto que se devuelve, en este caso Optional<String>. Si usáramos map() sobre getAccount() el resultado sería Optional<Optional<ClientOptional>>. FIN: Una de las partes más importantes es poder obtener el valor dentro de un Optional.
  19. 1: Para obtener el valor dentro de un Optional utilizaremos get(). Si el Optional estuviera vacío se lanzaría un NoSuchElementException 2: Si quisiéramos devolver un valor predeterminado en caso de estar vacío el Optional, utilizaremos orElse(). 3: Si quisiéramos construir el valor por defecto sólo si el Optional estuviera vacío usaríamos orElseGet(). 4: En caso de querer lanzar una excepción si el Optional estuviera vacío, usaremos orElseThrow. 5: Finalmente, en caso de querer ejecutar una acción determinada en caso de no estar vacío, utilizaríamos ifPresent(). FIN: Para terminar, Optional nos da la posibilidad de rechazar determinados valores.
  20. Mediante el método filter(), podemos rechazar los valores que consideremos dentro de un Optional. En este caso, estamos rechazando los valores impares, de modo que si myInteger fuera 11, i sería un Optional vacío. Un caso de uso típico es la ejecución de una acción después de la obtención de un resultado, como puede ser este caso.
  21. El fin. Si os ha gustado la presentación ya sabéis, acepto cerveza gratis.