Be real careful with pass by reference in Java

If you search for information about java pass by reference and pass by value you’ll get a lot of different info. You’ll find plenty of articles on the subject. Do some digging and you’ll find that java is always pass by value, but there are some times it looks a lot of like pass by reference. Here’s a quick example

import java.util.HashMap;
import java.util.Map;
public class PassByReference {
public static void main(String[] args) {
System.out.println("hello world");
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("OldValue", 1);
System.out.println(map);
addToCollection(map);
System.out.println(map);
}
static private void addToCollection(Map<String, Integer> map)
map.put("NewValue", 2);
}
}

This little snippet will print out

{OldValue=1}
{OldValue=1, NewValue=2}

Because when we make the call to addToCollection we’re actually passing a reference to the array, and we have the ability to modify it in the original scope.

In this trivial example it’s easy to say, “Oh I’d never do that.” But what if you have multiple maps to update?

import java.util.Map;
public class PassByReference {
public static void main(String[] args) {
System.out.println(“hello world”);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put(“OldValue”, 1);
System.out.println(map);
addToCollection(map);
System.out.println(map);
}
static private void addToCollection(Map<String, Integer> map, Map<String, Integer> map2){
map.put(“NewValue”, 2);
map2.put("NewerValue", map.get("NewValue") * 10);
}
}

Suddenly it’s a little more complicated. Should you create a method that takes two maps as input and only updates one? Should you refactor so you only use one map if you can? Should you use pass by reference, but comment on it so it’s clear what you’re doing and why?

As with all questions in software engineering the only valid answer is, “It depends.” And whether or not pass by reference is safe for your use case will be up to you, but consider it carefully. It’s easy for the next engineer maintaining that code to miss what your pass by reference function is doing. They may try to change behavior without realizing what’s happening.

Preventing unexpected changes to your object is one of the core goals of Immutability, and you can get access to immutable collections using Google’s Guava package for java. The ImmutableMap class provides an interface that will let most of the normal java collections methods work, but will not allow updates to the map objects once it’s created.

If we were to call our addToCollection method with

addToCollection(ImmutableMap.of());

We would get an exception when it tried to insert a new value. Use a little caution with this approach too — if something you depend on expects to be able to modify maps you could get unexpected exceptions here too.

All of that to say, programming is hard! Good luck!

--

--

--

Engineer, formerly at Amazon, currently at Google. All opinions are my own. Consider supporting here: https://devblabs.medium.com/membership

Love podcasts or audiobooks? Learn on the go with our new app.

Archiving web page on iPad Pro 10.5

Why I fell in love with Visual Studio Code.

How to Install DVWA Into Your Linux Distribution

Docker Compose Seed

What’s Trending in the Dev Community?

Tech to Keep an Eye Out for in 2022

Why Visual Programming Doesn’t Suck

This Week In TurtleCoin (July 21, 2020)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brian Olson

Brian Olson

Engineer, formerly at Amazon, currently at Google. All opinions are my own. Consider supporting here: https://devblabs.medium.com/membership

More from Medium

Java Reflections and Why it’s Black Magic

KivaKit — Logging Isn’t Special

Not stagnation, but regression of Java. Where modern Java 17 loses to Java 8

The Full-stack Dev Is Bent Out of T-shape