makadeade
home about archive (feed)

Diff-friendly formatting: switch statements

Published: November 10th 2025 (week 46 of 2025)

Because reviewing patches should not be made more difficult than it already is.

Switch statements

If you have a deep, desperate need to put everything on a single line this may look good to you:

switch (foo) {
case E_WHATEVER_FOO: x = 1; break;
case E_WHATEVER_BAR: x = 2; break;
case E_WHATEVER_BAZ: x = 3; break;
default: x = 0; break;
}
    

However, I would say this is way better:

switch (foo) {
case E_WHATEVER_FOO:
    x = 1;
    break;
case E_WHATEVER_BAR:
    x = 2;
    break;
case E_WHATEVER_BAZ:
    x = 3;
    break;
default:
    x = 0;
    break;
}
    

Why? Because if you want to keep the code neatly aligned on columns, this happens when you introduce a new case that is longer than all the already existing ones:

@@ -1,6 +1,7 @@
 switch (foo) {
-case E_WHATEVER_FOO: x = 1; break;
-case E_WHATEVER_BAR: x = 2; break;
-case E_WHATEVER_BAZ: x = 3; break;
+case E_WHATEVER_FOO:  x = 1; break;
+case E_WHATEVER_BAR:  x = 2; break;
+case E_WHATEVER_BAZ:  x = 3; break;
+case E_WHATEVER_QUUX: x = 4; break;
 default: x = 0; break;
 }
    

This is madness.

Of course, you can say that you may first realign the code and then push the real patch. If you are using an code formatter you cannot, not really, since the tool works on existing code. What you could do is push the real patch in a not-neatly-aligned form, and then push a "format code" patch. Either approach is ridiculous.

Just do the sensible thing and write code the proper way. Thank you from the mountain.

Tags

Next: Gamers Nexus and the Meaning of Punk

Previous: Hangover Square (1945)