Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Spring Data still using null references as return values?

Tags:

spring-data

This is more a suggestion for improvement than a question.

We all know about Tony Hoare's "billion dollar mistake" by inventing the null reference. Google advices in the wiki of the guava library to avoid using null.

I really appreciate the Spring Data project and we use Spring Data MongoDB in many projects. Is there a chance that you will replace all possible null reference return values by an Optional<T>? I think this would be a big improvement when using the Spring Data repositories abstraction.

I know that a lot of the interfaces would have to be changed, but the code changes are almost trivial, just wrap the return type in an Optional.of(returnValue).

like image 519
Marcel Härle Avatar asked Sep 17 '14 06:09

Marcel Härle


3 Answers

Guava/JDK8 Optional<T> support has already been introduced with RC1 of Release Train Dijkstra. Please have a look at the spring-data-examples for java8 to see how it works.

interface CustomerRepository extends Repository<Customer, Long> {

  // CRUD method using Optional
  Optional<Customer> findOne(Long id);

  // Query method using Optional
  Optional<Customer> findByLastname(String lastname);
}

BTW: there's support for default methods as well.

like image 134
Christoph Strobl Avatar answered Sep 29 '22 23:09

Christoph Strobl


I think, once Spring Data can drop the support for JDK versions older than JDK 8, it should be fairly easy to use the JDK 8 Optional. However, since this would change the whole API, you would have to release a new major version, along with upgrade paths etc. (the code change would be trivial, but not the consequences for the users of Spring Data).

like image 23
dunni Avatar answered Sep 29 '22 23:09

dunni


With the latest and greatest versions of Spring Data the CrudRepository now actually returns `Optional

like image 30
Jens Schauder Avatar answered Sep 30 '22 00:09

Jens Schauder