Member-only story
Returning Collections From Methods in Java
Never return null in place of a collection
Writing software often means fetching and returning data. In an object-oriented language like Java, we generally express data in terms of properties of a class. Unlike many newer OO languages, Java doesn’t offer properties as a first-class construct, so we instead use JavaBean getters and setters, in order to maintain encapsulation. As a result, most of us have grown accustomed to writing code like the following:
public class MyClass {
private String data;
public String getData() { return this.data; }
public void setData(String data) { this.data = data; }
}
In the example above, we see a simple class with a simple property: a String
called data. Of course, data can either contain a value, or it can be null.
How do we deal with Collection
-type properties? Let’s fabricate a simple class that encapsulates a List
:
public class MyClass { private List<String> myStrings;}
We have a field — a List of String
s — called myStrings
, which is encapsulated in MyClass
. Now, we need to provide accessor methods:
public class MyClass { private List<String> myStrings; public void setMyStrings(List<String> s) {
this.myStrings = s;
} public List<String> getMyStrings() {
return this.myStrings;
}}
Here we have a properly-encapsulated — if verbose — class. So we’ve done good, right? Hold that thought.
Optional Lessons
Consider the Optional
class, introduced in Java 8. By now, you’ve probably heard the mantra that you should never return null from a method that returns an Optional
. Why? Consider the following contrived example:
public class Foo { private String bar; public Optional<String> getBar() {
// don't actually ever do this
return (bar == null) ? null : Optional.of(bar);
}}