Search code examples
javajava-7indentationreadabilitytry-with-resources

What is the code convention for formatting try-with-resources?


I'd like to know what the code convention is for formatting try blocks with resources, in particular with more than one resource. Currently I put each resource on its own line, terminated by a semicolon, and use vim's indentation level (2 tab characters), like the following:

try (
        InputStream in1 = ...;
        InputStream in2 = ...;
    ) {
    ...;
}

I have also seen people use semicolon as a seperator rather than a terminator, and only use a newline between each resource like the following:

try (InputStream in1 = ...;
    InputStream in2 = ...) {
    ...;
}

What is the convention?


Solution

  • There is no "right" or "wrong" when aesthetics is involved; and each organization ends up converging on its own coding style. However, it is frequent to borrow coding styles from well-known projects or organizations.

    One of the most-used Java code-bases is the JDK itself. After a few greps, I found a multi-line example in OpenJDK 8's java/lang/Package.java:

    /*
     * Returns the Manifest for the specified JAR file name.
     */
    private static Manifest loadManifest(String fn) {
        try (FileInputStream fis = new FileInputStream(fn);
             JarInputStream jis = new JarInputStream(fis, false))
        {
            return jis.getManifest();
        } catch (IOException e) {
            return null;
        }
    }
    

    (there may be other examples within the JDK, but generally speaking, these people are serious about sticking to their guidelines, so I doubt that they will differ).