OdeToCode IC Logo

The Lost Art of Right Aligning Code

Tuesday, March 19, 2019

When I started working with the Go language using Visual Studio Code a few months ago, the Go extension for VS Code auto-formatted one type definition like so:

type ResourceInfo struct {
    ResourceID         string
    SubscriptionID     string
    GroupName          string
    Name               string
    Type               string
    RunID              string
    DocumentType       string
    Location           string
    LocationMisAligned bool
}

When I was a C / C++ developer I created and read right-aligned code all the time. The alignment makes patterns in code easier to find. For another example in Go, it’s easier to see which entries point to a "no-operation" function in the following hash map, because you can scan vertically down the file.

var resourceMap = map[string]func(*ResourceInfo) {
    "Microsoft.Sql/servers":           visitSQLServer,
    "Microsoft.Sql/servers/databases": noop,
    "Microsoft.Cache/Redis":           visitRedisCache,
    "Microsoft.Web/sites":             visitWebSite,
    "Microsoft.Portal/dashboards":     noop,
    // ...
}

Keeping code aligned requires some work, and without tool support it is rare to see the convention in .NET languages. The only tool I've found that comes close to supporting this style is the Always Algined extension for Visual Studio.


Comments
Gravatar Paul Tuesday, March 19, 2019
I've always liked formatting code this way. Only negative is that everyone in the team knows it 'your' code ;-)
Gravatar Roland Wednesday, March 20, 2019
I used to align code back in my Asssembly and C days. I stopped doing it when .NET came out. The .NET framework's long identifier names can cause a huge difference between e.g. type names in subsequent lines (e.g. "int" vs. "SharedConnectionWorkflowCommitWorkBatchService"). In fact, the long identifier names made me start using proportional fonts for coding (makes long identifier names much easier to read). This in turn means that I can only align the start of a line - which felt like a huge limitation at first, but then I noticed that I spent less time fiddling around with alignment e.g. of end-of-line comments.
Gravatar Dan Schnau Wednesday, March 20, 2019
There is the "Align Assignments" extension, which maps the hotkeys Ctrl+Alt+] to aligning selected assignment operators. https://marketplace.visualstudio.com/items?itemName=VisualStudioPlatformTeam.AlignAssignments
Ian Saturday, March 23, 2019
Keeping code aligned requires some work,!
Your Comment