Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code formatting: is lining up similar lines ok? [closed]

Tags:

I recently discovered that our company has a set of coding guidelines (hidden away in a document management system where no one can find it). It generally seems pretty sensible, and keeps away from the usual religious wars about where to put '{'s and whether to use hard tabs. However, it does suggest that "lines SHOULD NOT contain embedded multiple spaces". By which it means don't do this sort of thing:

foo    = 1; foobar = 2; bar    = 3; 

Or this:

if      ( test_one    ) return 1; else if ( longer_test ) return 2; else if ( shorter     ) return 3; else                    return 4; 

Or this:

thing foo_table[] = {   { "aaaaa", 0 },   { "aa",    1 },   // ... } 

The justification for this is that changes to one line often require every line to be edited. That makes it more effort to change, and harder to understand diffs.

I'm torn. On the one hand, lining up like this can make repetitive code much easier to read. On the other hand, it does make diffs harder to read.

What's your view on this?

like image 370
Ned Avatar asked Sep 19 '08 13:09

Ned


People also ask

What is code formatting?

Source Code Format means a form of computer program, or any portion thereof, written in a programming language employed by computer programmers that must be compiled or otherwise translated before it can be executed by a computer.

What is code alignment?

Code alignment is the practice of formatting your code vertically to improve readability. Based on principles borrowed from mathematics and other disciplines, code alignment gives extra meaning to your code by lining up similar data in columns.


1 Answers

2008: Since I supervise daily merges of source code,... I can only recommend against it.

It is pretty, but if you do merges on a regular basis, the benefit of 'easier to read' is quickly far less than the effort involved in merging that code.

Since that format can not be automated in a easy way, the first developer who does not follow it will trigger non-trivial merges.

Do not forget that in source code merge, one can not ask the diff tool to ignore spaces :
Otherwise, "" and " " will look the same during the diff, meaning no merge necessary... the compiler (and the coder who added the space between the String double quotes) would not agree with that!

2020: as noted in the comments by Marco

most code mergers should be able to handle ignoring whitespace and aligning equals is now an auto format option in most IDE.

I still prefer languages which come with their own formatting options, like Go and its gofmt command.
Even Rust has its rustfmt now.

like image 171
VonC Avatar answered Oct 06 '22 08:10

VonC