Search code examples
coding-stylepretty-print

Do you try to make your code look pretty?


I might be one anal programmer, but I like code that looks good from a distance. I just found myself lining up a CSS style so that instead of this:

#divPreview {
    text-align: center;
    vertical-align: middle;
    border: #779 1px solid;
    overflow: auto;
    width: 210px;
    height: 128px;
    background-color: #fff"
}

it now looks like:

#divPreview {
    width: 210px;
    height: 128px;
    overflow: auto;
    text-align: center;
    vertical-align: middle;
    border: #779 1px solid;
    background-color: #fff";
}

I will almost always write numerical comparisons in order of size like

if (0 < n && n < 10)

instead of

if (0 < n && 10 > n)

and finally I will tend to arrange if-then-else code so that the THEN part is smaller than the ELSE part (cause the heavier stuff goes to the bottom, right?)

if (afflicted == true) {
  GetSome();
  HelpRight();
}
else {
  NowPlease();
}

ugh!

if (afflicted == false) {
  HowMuchTrouble();
}
else {
  IsItToDo();
  ThisReally();
}

aahhh

I could go on and on with more examples, but you get the idea...

Question: Am I alone in my neurosis here? What's your coding kink?


Solution

  • Any code style that makes you reorder things when code changes is bad.

    It would screw up diffs. You are using a version control system right?

    There's a few other things that would make your code prettier, but screw up diffs.

    Imagine this code:

    int foo = 42;
    int fooBar = 1024;
    

    Now let's make it prettier by lining up the = signs:

    int foo    = 42;
    int fooBar = 1024;
    

    But then we add another variable:

    int foo              = 42;
    int fooBar           = 1024;
    String nowLetsBeEvil = 6400;
    

    Now if you did a diff, all 3 lines have changed, when only the last one did.

    And there's more, lining up params between methods is bad

    sqrt(x + y, x - z);
    sqrt(x    , x    );
    

    The comma and semi-colon are nicely lined up, but if you ever change the code, you'll have to manually reformat all the sqrt lines that are together and screw up the diffs again.

    Basically, never do manual formatting. Always enforce code styles using an IDE or pretty printer. But also never choose a code style where the format will change when your code did not

    EDIT:

    As stated in the comments, some diff tools can ignore whitespaces within lines. This is great, but not all diff tools can do this. If you are aligning fields or params, make sure you are:

    1. Not doing it manually
    2. Your diff tool can ignore the whitespace changes