Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: JM Brun
Added: Mar 26, 2018 4:52 PM
Views: 26
  1. //https://softwareengineering.stackexchange.com/questions/364211/why-use-optional-in-java-8-instead-of-traditional-null-pointer-checks
  2. // Old bad way
  3. Employee employee = employeeServive.getEmployee();
  4. if(employee!=null){
  5.     System.out.println(employee.getId());
  6. }
  7.  
  8. // Wrong way Java8
  9. Optional<Employee> employeeOptional = Optional.ofNullable(employeeService.getEmployee());
  10. if(employeeOptional.isPresent()){
  11.     Employee employee = employeeOptional.get();
  12.     System.out.println(employee.getId());
  13. }
  14.  
  15. // ----------------- Good way
  16. // Changed EmployeeServive to return an optional, no more nulls!
  17. Optional<Employee> employee = employeeServive.getEmployee();
  18. employee.ifPresent(e -> System.out.println(e.getId()));
  19.  
  20. Optional<Employee> employee = employeeServive.getEmployee();
  21. // Sometimes an Employee has forgotten to write an up-to-date timesheet
  22. Optional<Timesheet> timesheet = employee.flatMap(Employee::askForCurrentTimesheet);
  23. // We don't want to do the heavyweight action of creating a new estimate if it will just be discarded
  24. client.bill(timesheet.orElseGet(EstimatedTimesheet::new));