Better Programming

Advice for programmers.

Follow publication

Member-only story

Returning Collections From Methods in Java

Dave Taubler
Better Programming
Published in
6 min readJan 17, 2020
Photo by Ella Olsson on Unsplash

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 Strings — 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);
}
}

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Dave Taubler
Dave Taubler

Written by Dave Taubler

Software architect, engineering leader, musician, husband, dad

Responses (3)

Write a response