javawhitespacecheckstylereadabilitycode-readability

Reasoning behind no space between Generic brackets in Java


Looking at GenericWhitespaceCheck in Checkstyle documentation,

Left angle bracket (<):

  • should be preceded with whitespace only in generic methods definitions.
  • should not be preceded with whitespace when it is precede method name or following type name.
  • should not be followed with whitespace in all cases.

Right angle bracket (>):

  • should not be preceded with whitespace in all cases.
  • should be followed with whitespace in almost all cases, except diamond operators and when preceding method name.

I am not sure I fully understand the reasoning behind why < should not be followed by a space and why > should not be preceded by one.

In other words, why is Map<String> the convention over Map < String >?

Is this only because as the number of parameters and depth increases it, the without spaces version is more readable.

Like, Map<String, List<String>> is more readable than, Map < String, List < String > >?

Also, as a general question, are there some repository or guides which explain reasons behind Checkstyle conventions?


Solution

  • Although I have no evidence or research to base my theory on, I'd reason as follows:

    Cohesion

    A (kind of language-philosophical) rationale could be:

    The parametrization of types (generic's major role) such as in Map<String, Object> belongs to the type-name the same like parentheses and parameters belong to the method-name. So adding parameter to a signature should follow a consistent spacing-rule: no space around parametrizing brackets (neither in generic-type's parameter definition, nor in method's parameter definition).

    Thus the angle brackets are coherently defining the "type signature" and should stay as close to the type as possible (semantic and spatial), which means no space should untie this relation.

    Readability

    From the (Clean Code) perspective there is a clear benefit for avoiding spaces:

    Spaces around angle brackets rather make them misread or misinterpreted as logical comparison operators.