Poutsma Principles Consulting & Training

'as' vs 'to' in Method Names

What is the difference between a method named toSomething() and one named asSomething()? For example: what distinguishes a toMap() method from an asMap() method?

The key difference lies in expectations about how the returned value relates to the original object.

to – Detached Conversion

When a method name starts with to, it typically converts internal data into a new representation and returns it. The returned object is detached—that is, it has no connection to the original.

as – Linked Representation

In contrast, a method starting with as usually exposes an alias of the internal data. This alternative representation is connected to the original, meaning changes made to either the alias or the original will be reflected in the other.

Examples from the JDK

This naming pattern is used throughout the JDK. Consider:

  • Collection::toArray():
    The Javadoc makes it clear that the returned array is independent:

    The returned array will be “safe” in that no references to it are maintained by this collection.

  • Arrays::asList(T...):
    Here, the Javadoc explicitly states the alias is connected:

    Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array.

ByteBuffer

The java.nio package is another area where both as and to methods are used. For example, compare ByteBuffer::asCharBuffer(), which returns a connected alias, with ByteBuffer::toString, which produces a detached representation.

Code Examples

Using asList()

String[] array = new String[]{"foo"};
List<String> list = Arrays.asList(array); // List alias of the array

list.set(0, "bar"); // change the alias
System.out.println(array[0]); // "bar"
System.out.println(list);     // "[bar]"

array[0] = "baz"; // change the original
System.out.println(array[0]); // "baz"
System.out.println(list);     // "[baz]"

Using toArray()

List<String> list = new ArrayList<>();
list.add("foo");
String[] array = list.toArray(new String[1]); // convert list to array

array[0] = "bar"; // modify the detached array
System.out.println(list);     // "[foo]"
System.out.println(array[0]); // "bar"

list.set(0, "baz"); // modify the original list
System.out.println(list);     // "[baz]"
System.out.println(array[0]); // "bar"

A Rule of Thumb

If you start a method name with as, make sure the returned object stays linked to the original. Otherwise, you will create misleading expectations.


About the Author

I am Arjen Poutsma, and I help teams improve Java code, design better APIs, and manage open source—through reviews, training, and coaching. If that sounds useful, please contact me.