日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

动手选择值

發布時間:2023/12/3 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 动手选择值 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

由于冠狀病毒的存在,可選的東西在空中,一切都變得可選,例如可選的公共聚會,可選的在家工作,可選的旅行等。

我現在是時候談論處理NULL引用的軟件工程中真正的“ 可選 ”了。

托尼·霍爾(Tony Hoare)坦言,他發明了空(Null)犯了數十億美元的錯誤。 如果您還沒有看過他的演講,那么我建議您看一下Null-References-The-Billion-Dollar-Mistake 。

我將與null分享一些反模式 ,以及如何使用Optional或MayBe之類的抽象方法解決它。

在此示例中,我們將使用可以包含一些空值的簡單值對象。

public class Person {final String firstName;final String lastName;final String email; // This can be nullfinal String phone; //This can be null }

該值對象的電子郵件和電話號碼可以為空值。

方案:電子郵件和電話號碼上的聯系人

不使用可選

第一次嘗試將基于檢查null,如下所示

//Not using optionalif (p.email != null) {System.out.println("Sending email to " + p.email);}if (p.phone != null) {System.out.println("Calling " + p.phone);}

這就是多年來所做的。 具有收集結果的另一種常見模式。

List<Person> p = searchPersonById("100");if (p.isEmpty()) {System.out.println("No result");} else {System.out.println("Person" + p.get(0));}

以錯誤的方式使用可選

Optional<String> phone = contactNumber(p);Optional<String> email = email(p);if (phone.isPresent()) {System.out.println("Calling Phone " + phone.get());}if (email.isPresent()) {System.out.println("Sending Email " + email.get());}

這樣做好一點,但是通過在代碼中添加if / else塊,將Optional的所有好處都拋棄了。

永遠快樂可選

//Always HappyOptional<String> phone = contactNumber(p);Optional<String> email = email(p);System.out.println("Calling Phone " + phone.get());System.out.println("Sending Email " + email.get());

很高興感到高興,但是當您嘗試使用Optional時,您所做的假設很大,或者您不需要Optional。

嵌套屬性可選

在這種情況下,我們將擴展Person對象并添加Home屬性。 并非每個人都可以擁有房屋,因此最好不要使用該房屋。 讓我們看看在這種情況下聯系人場景如何工作

//Nested Propertyif (p.getHome() != null) {System.out.println("Sending Postal mail " + p.getHome().address);}if (p.getHome() != null && p.getHome().getInsurance() != null) {System.out.println("Sending Notification to insurance " + p.getHome().getInsurance().getAgency());}

在這里,代碼將具有大量嵌套的空檢查變得越來越糟。

基于優先級的默認

對于這種情況,我們首先嘗試通過家庭住址與他人聯系,如果該人不可用,則請通過辦公地點與他人聯系。

//Address has priority , first home and then Officeif (p.home != null) {System.out.println("Contacted at home address " + p.home.address);return; // Magical return for early exit}if (p.office != null) {System.out.println("Contacted at office address " + p.office.address);return; // Magical return for early exit}

這種類型的場景需要使用提前控制流來盡早返回,并使代碼難以理解和維護。

這些是一些常見模式,其中未使用可選選項或使用了錯誤的方式。

可選使用方式

讓我們看看一些使用可選的好方法。

根據領域知識使屬性可選

使屬性成為可選屬性非常容易。

public Optional<String> getEmail() {return Optional.ofNullable(email);}public Optional<String> getPhone() {return Optional.ofNullable(phone);}

是的,允許將其設為“可選”,沒有人會為此而絞盡腦汁,并且可以毫無恐懼地隨意這樣做。 更改完成后,我們可以編寫如下內容

//Use Optionalp.getEmail().ifPresent(email -> System.out.println("Sending email to " + email));p.getPhone().ifPresent(phone -> System.out.println("Calling " + phone));//Optional for Collection or Search type of requestOptional

It looks neat, first step to code without explicit if else on application layer.

Use some power of Optional

//Use IfPresent & other cool thingsphone.filter(number -> hasOptIn(number)).ifPresent(number -> System.out.println("Calling Phone " + number));email.filter(m -> hasOptIn(m)).ifPresent(m -> System.out.println("Sending Email " + m));

Optional is just like stream, we get all functional map,filter etc support. In above example we are checking for OptIn before contacting.

Always happy optional

Always happy optional that calls "get" without check will cause runtime error on sunday midnight, so it advised to use ifPresent

//Don't do thisSystem.out.println("Calling Phone " + phone.get());System.out.println("Sending Email " + email.get());//Use ifPresent to avoid runtime errorphone.ifPresent(contact -> System.out.println("Sending email to " + contact));email.ifPresent(contact -> System.out.println("Calling " + contact));

Nested Optional

p.getHome().ifPresent(a -> System.out.println("Sending Postal mail " + a.address));p.getHome().flatMap(Person.Home::getInsurance).ifPresent(a -> System.out.println("Sending Notification to insurance " + a.agency));

Flatmap does the magic and handles null check for home and convert? insurance object also.

Priority based default

//Address has priority , first home and then OfficeOptional<String> address = Stream.of(person.getHome().map(Home::getAddress), person.getOffice().map(Office::getAddress)).filter(Optional::isPresent).map(Optional::get).findFirst();address.ifPresent(add -> System.out.println("Contacting at address " + add));

This example is taking both home & office address and pick the first one that has value for sending notification. This particular pattern avoids lots of nested loops.

Else branch

Optional has lots of ways to handle else part of the scenario like returning some default value(orElse) , lazy default value (orElseGet) or throw exception(orElseThrow).

What is not good about optional

Each design choice has some trade off and optional also has some. It is important to know what are those so that you can make careful decision.

Memory indirection

As optional is container , so every access to value need extra jump to get real value. Optional is not good choice for element in array or collection.

No serialization

I think this is good decision by Jdk team that does not encourage people to make instance variable optional. You can wrap instance variable to Optional at runtime or when required for processing.

翻譯自: https://www.javacodegeeks.com/2020/03/hands-on-optional-value.html

總結

以上是生活随笔為你收集整理的动手选择值的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。