Monday, 29 September 2014

Java 8 : Null? no thanks!

You know, I know, they know, everybody knows, returning null from a public method is often a bad practice.
Reasons are multiple, from the risk of raising NullPointerException in runtime to the horrible == null check in your code.

To avoid returning nulls in Java 8 you can use java.util.Optional (if you are on previous version of Java, Guava has similar functionality).

package com.marco;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class NoNullsThanks {

        private final Map<String, Integer> nameAge = new HashMap<String, Integer>();

        public Integer getAge(String name) {
                return Optional.ofNullable(nameAge.get(name)).orElse(-1);

        private final Map<String, List<String>> nameEmails = new HashMap<String, List<String>>();

        public List<String> getEmails(String name) {
                return Optional.ofNullable(nameEmails.get(name)).orElse(new ArrayList<String>());

Nice & Clean :)

No comments:

Post a Comment