Black for C++: what if your indentation was your syntax tree?
I recently wrote a line of C++ that took me three passes to read. It was not clever code. It was an ordinary constructor initializer list. Display :: Display ( Keyboard & keyboard , int output , const Vector & position , const Vector & size , const Vector & expandTo , Screen screen ) : keyboard_ ( keyboard ) , output_ { output } , screen_ { screen } , cursor_ ( enter ( position ) ) ,…
The author of the provided C++ code experienced difficulty understanding the syntax tree of an indentation-heavy constructor initializer list. Most C++ formatting aligns lines based on a column budget, which does not provide clarity on the structure of the code. The nested conditional in the code example made it particularly challenging to discern the relationships between different elements.
Structured indentation offers a solution to this problem. This approach follows four simple rules that align with the syntax of the code. Contexts that do not fit on a line begin with their opening token at the end of the line, followed by indented contents. Contexts with an opening token but no closing token, such as the ternary operator, are indented after the token and dedented when the context ends. Items within an indented block are written one per line, making the structure more apparent.
When applying structured indentation to the example code, the resulting output demonstrates a more readable and organized format. The visual line, as defined by the structured indentation spec, ensures that the contents of a context form a contiguous block, with closing tokens returning to the column of their opener. This maintains the code's shape at any depth, allowing for easy comprehension of the relationships between different elements.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to