动手学习_动手选择值
動手學習
由于冠狀病毒的存在,可選的東西在空中,一切都變得可選,例如可選的公共聚會,可選的在家工作,可選的旅行等。
我現(xiàn)在是時候談論處理NULL引用的軟件工程中真正的“ 可選 ”了。
托尼·霍爾(Tony Hoare)坦言,他發(fā)明了空(Null)犯了數(shù)十億美元的錯誤。 如果您還沒有看過他的演講,那么我建議您看一下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 }該值對象的電子郵件和電話號碼可以為空值。
方案:電子郵件和電話號碼上的聯(lián)系人
不使用可選
第一次嘗試將基于檢查null,如下所示
這是多年來所做的。 具有收集結果的另一種常見模式。
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的所有優(yōu)點都拋棄了。
永遠快樂可選
//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屬性。 并非每個人都可以擁有房屋,因此最好不要使用該房屋。 讓我們看看在這種情況下聯(lián)系人場景如何工作
在這里,代碼將具有大量嵌套的空檢查變得越來越糟。
基于優(yōu)先級的默認
在這種情況下,我們首先嘗試通過家庭住址與他人聯(lián)系,如果該人不可用,則請通過辦公地點與他人聯(lián)系。
這種類型的場景需要使用提前控制流來盡早返回,并使代碼難以理解和維護。
這些是一些常見模式,其中未使用可選選項或使用了錯誤的方式。
可選使用方式
讓我們看看一些使用可選的好方法。
根據(jù)領域知識使屬性為可選
使屬性成為可選屬性非常容易。
是的,允許將其設為“可選”,沒有人會為此而絞盡腦汁,并且可以毫無恐懼地隨意這樣做。 更改完成后,我們可以編寫如下內容
//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 requestOptionalIt 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
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
動手學習
總結
以上是生活随笔為你收集整理的动手学习_动手选择值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ps怎么查看字体颜色(ps怎么查看字体颜
- 下一篇: ps3怎么解除图层(ps3d图层怎么退出