Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Null References The Billion Dollar Mistake | Java 8 Optional Example | Haskell Kotlin | InterviewDOT

Автор: Interview DOT

Загружено: 2020-06-26

Просмотров: 2006

Описание:

Click here -    / @interviewdot   to get notifications.

Null References The Billion Dollar Mistake | Java 8 Optional Example | Haskell Kotlin | InterviewDOT

Make your code more readable and protect it against null pointer exceptions.

A wise man once said you are not a real Java programmer until you've dealt with a null pointer exception. Joking aside, the null reference is the source of many problems because it is often used to denote the absence of a value. Java SE 8 introduces a new class called java.util.Optional that can alleviate some of these problems.

What's possibly problematic with the following code?

String version = computer.getSoundcard.getUSB.getVersion;

This code looks pretty reasonable. However, many computers for example, the Raspberry Pi don't actually ship with a sound card. So what is the result of getSoundcard?

A common bad practice is to return the null reference to indicate the absence of a sound card. Unfortunately, this means the call to getUSB will try to return the USB port of a null reference, which will result in a NullPointerException at runtime and stop your program from running further. Imagine if your program was running on a customer's machine; what would your customer say if the program suddenly failed?

To give some historical context, Tony Hoare—one of the giants of computer science—wrote, "I call it my billion-dollar mistake. It was the invention of the null reference in 1965. I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement."

What Alternatives to Null Are There?
Languages such as Groovy have a safe navigation operator represented by "?." to safely navigate through potential null references. Note that it is soon to be included in C#, too, and it was proposed for Java SE 7 but didn't make it into that release. It works as follows:

String version = computer?.getSoundcard?.getUSB?.getVersion;

In this case, the variable version will be assigned to null if computer is null, or getSoundcard returns null, or getUSB returns null. You don't need to write complex nested conditions to check for null.

In addition, Groovy also includes the Elvis operator "?:" if you look at it sideways, you'll recognize Elvis' famous hair, which can be used for simple cases when a default value is needed. In the following, if the expression that uses the safe navigation operator returns null, the default value "UNKNOWN" is returned; otherwise, the available version tag is returned.

Optional in a Nutshell
Java SE 8 introduces a new class called java.util.Optional T that is inspired from the ideas of Haskell and Scala. It is a class that encapsulates an optional value, as illustrated in Listing 2 below and in Figure 1. You can view Optional as a single-value container that either contains a value or doesn't it is then said to be "empty"

n itself, zero references are not a bad concept - after all, you also have to be able to represent the absence of a value, but zero references hold many dangers in careless hands: misleading APIs, boilerplate code (zero checks), countless NPEs.


With Java 8, a potential solution to the problem was introduced with the Optional class: a container for objects cannot be guaranteed to exist throughout their life cycle. The idea behind it: by returning a value as optional, I indicate that it may not exist and force callers to take care of this case. This prevents many possible NPEs.

While this is basically a step in the right direction, it also leads to misuse and incorrect use. In the following, scenarios with typical errors when using optionals and possible solutions are presented.

HERE ARE A FEW MORE RULES OF THUMB:
Collections of optionals are almost always superfluous. Instead, collections should always be initialized empty or methods should return empty collections.
Optionals should never be used as transfer parameters. Instead, methods should be overloaded: if a parameter is optional, another signature is offered in which it is not available.

Null References The Billion Dollar Mistake | Java 8 Optional Example | Haskell Kotlin | InterviewDOT

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Исключения нулевого указателя в Java — что это такое и как их исправить

Исключения нулевого указателя в Java — что это такое и как их исправить

Опции в Java — простое руководство

Опции в Java — простое руководство

Как взломать любое программное обеспечение

Как взломать любое программное обеспечение

Почему любители часто круче «профессионалов»?

Почему любители часто круче «профессионалов»?

Сокращения в Айти. Пузырь лопнул

Сокращения в Айти. Пузырь лопнул

Самый короткий тест на интеллект Задача Массачусетского профессора

Самый короткий тест на интеллект Задача Массачусетского профессора

Optional Class in Java 8 - Avoid Null Pointer Exception | Java 8 Features | Crash Course ✅

Optional Class in Java 8 - Avoid Null Pointer Exception | Java 8 Features | Crash Course ✅

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Typst: Современная замена Word и LaTeX, которую ждали 40 лет

Does Rust solve the billion dollar mistake?

Does Rust solve the billion dollar mistake?

Java Anonymous Inner Classes Explained in 6 Minutes

Java Anonymous Inner Classes Explained in 6 Minutes

Мой опыт перехода с MacOS на Linux | Полный гайд

Мой опыт перехода с MacOS на Linux | Полный гайд

Для Чего РЕАЛЬНО Нужен был ГОРБ Boeing 747?

Для Чего РЕАЛЬНО Нужен был ГОРБ Boeing 747?

Difference between ClassNotFoundException and NoClassDefFoundError

Difference between ClassNotFoundException and NoClassDefFoundError

5 Reasons Why Most Devs NEVER Improve

5 Reasons Why Most Devs NEVER Improve

Thoughts About Unit Testing | Prime Reacts

Thoughts About Unit Testing | Prime Reacts

Java Optional Explained

Java Optional Explained

Как реорганизовать невероятно сложную бизнес-логику (шаг за шагом)

Как реорганизовать невероятно сложную бизнес-логику (шаг за шагом)

Java ВСЕГДА использует передачу по значению. Вот почему

Java ВСЕГДА использует передачу по значению. Вот почему

SAMOBÓJ I 106. GOL LEWANDOWSKIEGO W LIDZE MISTRZÓW! | SLAVIA - FC BARCELONA, SKRÓT MECZU

SAMOBÓJ I 106. GOL LEWANDOWSKIEGO W LIDZE MISTRZÓW! | SLAVIA - FC BARCELONA, SKRÓT MECZU

5 уровней C++

5 уровней C++

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com