Guava-optional Nullable types

Source: Internet
Author: User
Tags google guava

Next to the guava joiner and splitter, this article will introduce another useful guava object optional, which in Java Google Guava first presented us with a nullable object model. In other languages such as C # This is a pattern that has existed for a long time and is included in the. NET class Library Nullable (Int? is also a nullable type).

Null sucks

Return to this topic optional. In my daily programming, NullPointerException is definitely the most unusual error we have encountered:

For this, Doug Lea once said:

Null sucks.

Sir C. R. Hoare also said:

I call it my billion-dollar mistake.

From above we can see the frequency of Nullpointerexceptiond and the hateful place. So in Gof's design pattern We also put forward the empty object pattern (or special case mode) to deal with this abominable nullpointerexceptiond. The empty object pattern replaces null objects primarily by returning certain objects that are meaningless and do not affect the processing logic , thus avoiding the judgment of unnecessary null objects. For example, when calculating the total payroll for a group of employees, we can return the default value for the returned null object to the employee object for 0 pay, then we do not need to make any null judgments.

Employee Pay Issues

Then how to solve the optional in guava? Before we explain the optional, let's take a look at the native Java code to calculate the total payroll for a group of employees in the future:

@TestPublic   void should_get_total_age_for_all_employees() throws  Exception {  final  list  <  employee  >  list  =  lists   newarraylist   ( new  employee   (  "em1"   30   new  employee   (  "em2"   40   null   new  employee   (  "em4"   18    int sum = 0;     For   (employee employee : list) {      if (employee! = null) {          sum + = employee. Getage ();            }        }     System.  out . println (sum);     } Private class Employee {  Private final String name;      Private final int age;     Public   Employee(String name, int.  ) {    This  . name = name ;        This  .  Age =  Age ;        }    Public   String getName() {      return name;         }    Public   int getage() {      return age;         }    }

If you switch to guava optional how to:

 @Test Public   void should_get_total_age_for_all_employees() throws  Exception {  final list<Employee> List = Lists . newarraylist (new Employee("em1" ),      New Employee("em2", +),          null,           New Employee("em4" );           int sum = 0;     For   (employee employee : list) {     sum + = Optional. fromnullable (employee). or (new Employee("dummy", 0)). Getage ();        }     System.  out . println (sum);     }

It is clear from the above that we are not worried about the object being empty, using optional's fromnullable to create a nullable object, and put it or a dummy employee information, so here we are not worried about Nullpointerexceptiond.

Maybe you can say and use the Trinocular operation (_?: _) No difference, in this case the function is really not much difference, but the individual feel guava more semantic, more general, and meet a lot of empty object pattern use of the scene.

Optional API

*. Optionalobject.ispresent (): Returns whether the object has a value.

*. Optional.absent (): Returns an empty Optional object, IsPresent () will return false

*. Optional.of (): Create Optional object, input parameter cannot be null

*. Optional.fromnullable (): Create Optional object, input can be null

*. Optionalobject.asset (): Merges with optional object values and returns a set of size 0 if NULL

*. Optionalobject.or (): Merge with optional object value and return or parameter as default if NULL is empty

*. Optionalobject.ornull (): Merges with optional object values and returns NULL as the default value if NULL is empty

The above API is our most common method of using optional, note that if we create a optional object, but do not determine whether the ispresent () exists, the direct get this will throw an exception, this is a disorderly use of the optional situation, and the direct use of NULL is no different.

final Optional<Object> obj = Optional.fromNullable(null);final Object o = obj.get();

The same optional is empty object mode, you can add the default value, NULL does not affect our processing, if NULL we can not continue the program processing situation, need to throw an exception or interrupt, or need to throw an exception, interrupt, The use of preconditions.checknotnull and so on, rather than continue to set a layer of optional objects, which is also a disorderly use of optional column.

Guava-optional Nullable types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.