Sunday, August 21, 2016

What is this method doing?

One-liner method passes its parameters untouched to anther method doesn't usually add value. I came across this method the other day, and wanted to look into it. I know this is not a one-liner.
private String base64EncodedFrom(byte[] bytes) {
   if (bytes == null) {
       return null;
   }
   return Base64.encodeBase64String(bytes);
}

Sure it checks if bytes array is null beforehand, its name is a bit more human readable, because of the From, than the one that it'll pass on. To make it even better, do you think the method name should be something like base64EncodedFromByteArrayNullSafe? Well, that's not my point, if you've read this post.

Let's check Base64.java
public static String encodeBase64String(final byte[] binaryData) {
   return StringUtils.newStringUtf8(encodeBase64(binaryData, false));
}

public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked) {
   return encodeBase64(binaryData, isChunked, false);
}

public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe) {
   return encodeBase64(binaryData, isChunked, urlSafe, Integer.MAX_VALUE);
}

public static byte[] encodeBase64(final byte[] binaryData, final boolean isChunked, final boolean urlSafe, final int maxResultSize) {
   if (binaryData == null || binaryData.length == 0) {
       return binaryData;
   }
...
}

Now we know encodeBase64() is null-safe. Let's then check StringUtils.java
public static String newStringUtf8(final byte[] bytes) {
   return newString(bytes, Charsets.UTF_8);
}


private static String newString(final byte[] bytes, final Charset charset) {
   return bytes == null ? null : new String(bytes, charset);
}

So newStringUtf8() is null-safe too. Now it's safe to rewrite the first method this way
private String base64EncodedFrom(byte[] bytes) {
   return Base64.encodeBase64String(bytes);
}
Do you still think base64EncodedFrom() is a method that adds value?