Over a million developers have joined DZone.

An importance of wrapping variables

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

Long time ago I developed a habit of wrapping every variable logged in [ .. ]:

Java:   log.error( "Class [" + c + "] not found" )
Java:   log.error( String.format( "Class [%s] not found", c ))
Groovy: log.error( "Class [$c] not found" )

The reasons were mostly to spot any trailing whitespaces in variables logged which was very helpful in error messages. As simple as it sounds, lots of messages thrown or logged today still don’t enclose variables in any special characters which can make them quite obscure.

What would you say about this error message ?

..
java.lang.IllegalArgumentException: No enum const class Something.
    at java.lang.Enum.valueOf(Enum.java:196)
..

I was surprised why failing Enum.valueOf() didn’t include the wrong value in the error message. But it did! Here’s the failing code:

..
enum Something{ A, B }
assert Something.A != Something.valueOf( '' )
..

So it was an empty String. Normally, wrong Enum.valueOf() input is printed:

.
enum Something{ A, B }
assert Something.A != Something.valueOf( 'C' )
 
java.lang.IllegalArgumentException: No enum const class Something.C
    at java.lang.Enum.valueOf(Enum.java:196)
..

But with empty argument "No enum const class Something." simply looked like a period at the end of the sentence! I wish it was "No enum const class [Something.]" instead.

// "java/lang/Enum.java"
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
                                            String name) {
    T result = enumType.enumConstantDirectory().get(name);
    if (result != null)
        return result;
    if (name == null)
        throw new NullPointerException("Name is null");
    throw new IllegalArgumentException(
        "No enum const " + enumType +"." + name);
}

 

From http://evgeny-goldin.com/blog/wrapping-variables/

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}