views:

2367

answers:

34

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?

+11  A: 

I'd probably go even further and do this :

#divPreview {
        width            : 210px;
        height           : 128px;
        overflow         : auto;
        text-align       : center;
        vertical-align   : middle;
        border           : #779 1px solid;
        background-color : #fff";
            }
Steve
:) .. yeah but .. hmm, i dunno .. that 'border' line looks out of place hmm ..
Scott Evernden
This looks a lot like my CSS!
sep332
i don't like those hanging braces, seems sloppy/unbalanced...
Steven A. Lowe
tabbing properties is the way to go!
jckeyes
I go alphabetical, left to right...
Brian Knoblauch
Pretty yes, easy to maintain NO. Your diff would also end up showing changes on lines where only the formatting changed.
Pyrolistical
Easy to read is easy to maintain. Personally I think the original question poster is being OCD without contributing to readability. Steve's tabbing, however, does increase the readability of the code. The diff is irrelevant; your tools are supposed to work for you, not the other way around.
Joel Wietelmann
I don't like the braces, but I am glad to see that I am not the only one who likes to have the columnar look to the declarations.
joseph.ferris
+9  A: 

it should be

if (!afflicted)
{
    HowMuchTrouble();
}
else 
{
    IsItToDo();
    ThisReally();
}

buy a prettyprinter, and get treated for OCD ;-)

Steven A. Lowe
LOL. However, I do think "if (afflicted == false)" is prettier than "if (!afflicted)", but that's my inner VB talking.
MusiGenesis
@MusiGenesis: you should see an exorcist about that inner VB thingy, sounds painful!
Steven A. Lowe
ugh! comparing a boolean value to true/false makes me cringe! If it's in code I have to maintain, it makes me angry.
Andrew Van Slaars
@MusiGenesis: In VB: "If Not afflicted Then ..."
P Daddy
@Andrew: Even worse is when they do something like: bool isGeorge = false; if(name == "George") isGeorge = true;Arg! Please just use `bool isGeorge = name == "George";`
P Daddy
@P Daddy: And please use parentheses!
Ferdinand Beyer
@Ferdinand Beyer: Please learn operator precedence order.
P Daddy
+3  A: 

Code should be easy to read an maintainable. "Pretty" is entirely consistent with those requirements, so long as you don't get too cute with it.

Jon B
+1  A: 

I always make my code look pretty. I find it easier to read. I format all variables and their values so they line up, and I use white space to logically group things together. I also try to declare variables in the order they are used and at the top of the scope they belong to.

Kevin
+21  A: 

Positive condition first in an if-else statement, always. Beauty lies within.

if (afflicted) {
    GetSome();
    HelpRight();
} else {
    NowPlease();
}
krosenvold
yeah but but .. that will almost Always put dangling little whimpy else-blocks in your code, no?
Scott Evernden
MOdified slightly to only pertain to if-else statements ;)
krosenvold
I do the postive-condition-first thing except in the "whimpy else-block" case. If there's a wimpy block and a beefy block, the wimpy one comes first so it is a bit more obvious. Then, I try to rewrite the condition variables so it again becomes a positive condition first.
Bryan Oakley
@Bryan; I normally prefer to exit the method for whimpy blocks. Or extract method for the beefy one.
krosenvold
My take on it is that you should always test for exceptions, never the normal case, http://stackoverflow.com/questions/114342/what-are-code-smells-what-is-the-best-way-to-correct-them/223881#223881.
hlovdal
+62  A: 

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
Pyrolistical
I completely agree here. This is very important to note!!
Mat Nadrofsky
If you're using a sane diff tool like DiffMerge, you can tell it to ignore "unimportant" differences like whitespace.
GalacticCowboy
But does it handle white spaces between identifiers on the same line?
Pyrolistical
Yep. I'll try to post a screen shot.
GalacticCowboy
We should change the diff tool to be more useful to us. Its machines that work for us, not the opposite.
Null303
True machines should work for us, and thus we shouldn't modify formatting by hand either.
Steve Tranby
DiffMerge, showing unimportant differences (note differences in highlighting): http://img185.imageshack.us/img185/5351/withunimportantdifferenue8.pngDiffMerge, not showing unimportant differences: http://img185.imageshack.us/img185/8641/withoutunimportantdiffedk2.png
GalacticCowboy
Beyond Compare also handles this nicely.
P Daddy
It is an interesting point. But I do not completely agree. Those space differences would anyway happen. See the version 1 and version to of this code at http://pastie.org/315160
ragu.pattabi
I completely disagree. Code written manually is meant to be read by humans, not machine. Thus, it should be as readable as possible.
Martin Cote
I really hate unaligned code. It's totally unreadable, and it's often the source of bugs, because it makes it more difficult to see if one of the lines contains a typo.
Wouter van Nifterick
Personally, since I started working in a source-control system, I tend to make changes with some paranoia for what the diff will look like when I'm done. While I sometimes restyling unrelated code (accidentally or something), I generally feel something in my bones that tells me "don't mess up the diff."
Ken Bloom
Other than the proposed DiffMerge by @GalacticCowboy, there are several ways to address this issue. How about just submitting the changed source to the repository with actual changes? It's important to consider the DIFFs, but it's way more important the code to be easily readable.
Cawas
+15  A: 

It is important to make code look "good" which is why we have conventions and style guidelines. The objective it to make code easy to read and to make wrong code look wrong. I would say that some of the examples here go beyond that and add little value.

Order of CSS Properties

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

I would find it more useful to be consistent in the order of the properties rather than making sure they are in ordered in ascending length for each selector. That convention makes it easier to find the one you are looking for.

Order of conditionals

You example here makes sense to me because it clearly shows n is between 0 and 10.

if (0 < n && n < 10)

Order of if/else blocks

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?)

I would think it makes more sense to have the positive condition first (or the more expected condition). And the "== true" bit is redundant.

if (afflicted) {
  GetSome();
  HelpRight();
}
else {
  NowPlease();
}
g .
Yup, regarding CSS: I always order my CSS properties alphabetically. I've seen many ways to group and sort them, but none so simple to follow as alphabetical order. Same goes with element selectors, classes and ids. And classes/functions/methods when it comes to code.
Blixt
+19  A: 

In my experience, pretty code usually works very well, while ugly code often breaks in hard-to-spot ways. It's just true that the kind of mind that pays attention to details like how the code looks is also the kind of mind that pays attention to more important details.

That said, re-ordering the elements in a CSS style so that they go short-to-long is bat**** crazy.

MusiGenesis
Don't every try to use asterisks in an answer.
MusiGenesis
Why no astericks?
Dining Philanderer
Try it and you'll see. I had to edit my post 10 times just to get bat**** to show up right.
MusiGenesis
+1 I think you've really hit it. Even after letting go of some truly compulsive habits, I still use "pretty" spacing quite often. When you have a number of repetitive statements, it makes errors much easier to spot. (As for CSS, I just keep properties in a certain order, irrespective of length.)
harpo
Oh, is that what he was going for? I was trying to figure out his reordering logic...
Matchu
+1  A: 

I don't see the point in your css example... Steve has a more readable example.

As for the if statements - I see no rhyme or reason to putting the heaviest at the bottom. I usually put the more commonly expected situation first.

DGM
+2  A: 

I go overboard with my OCD formatting, but I still think it's important to keep code as readable as possible unless you have a really compelling reason not to. The biggest reason: code you wrote over 6 months ago may as well have been written by someone else. Do yourself a favor and keep your code clean and consistent.

Dinah
+2  A: 
Federico Ramponi
diffs will fail with changing alignment of code
Pyrolistical
You can easily ignore white space in diffs. -iw
Scottie T
@Pyrolistical: maybe it's time to renew your diff software? It'll let you to write readable code without coming up with false positives, so it should be worth it.
Wouter van Nifterick
+4  A: 

I view it a little differently. Code should be formatted for readability, not necessarily"Prettiness"--although those two may usually be the same thing.

but as a counter case,

if(x != null)
    y=x.getParam();
else
    y=0;

is just more readable than the prettier:

y = x == null ? 0 : x.getParam();

I know the point is arguable, I totally get it and I love that operator and all, but for 95% of the programmers out there (including the next one to read your code) it's going to take a little bit more to parse.

In fact, I even had trouble with ruby's quite elegant:

y = x.getParam() if x

Simply because I'm so used to seeing control statements by scanning the left line of the code.

I do have to admit that I got a little weak in the knees when I saw this syntax (I think it's from hascal)

y = x?getParam();

That's a level of elegance that can even overpower my jaded perceptions.

Finally, although formatting can be really neat for bringing out patterns in your code, if you even HAVE patterns in your code you're probably not doing it right.

Whenever you have patterns in your code, look for a refactoring opportunity. Try to identify data and pull it out, then factor out the repeated parts of the pattern to be a loop of some sort that consumes the data.

By the way, your first example was data, not code--data very much needs formatting as well--maybe even more so.

Bill K
Call me crazy, but I actually find "y = x == null ? 0 : x.getParam();" easier to read than the if/else block.
Andrew Van Slaars
I know people say that (it's why I had a disclaimer), what I said was that 95% of the people don't see it that way. Since it takes no longer to read 3 lines, however, can you REALLY say that it's actually easier for you to read, or is it just that it feels so much more elegant?
Bill K
The one-liner places visual emphasis on the assignment, which is the primary operation here. The multiline version places emphasis on the decision, which is secondary and much less important. I try to make sure that the most important aspect of each operation is the most prominent.
P Daddy
I agree conceptually, but with the frequency you actually run into it combined with the fact that this is the only usage that makes it even slightly viable means that using it is, in general, costing development dollars.
Bill K
I actually find more use for it in function arguments -- DoSomething(a == null ? b : a) -- or in converting booleans to enums -- mask = (flag1 ? Enum.Value1 : 0) | (flag2 ? Enum.Value2 : 0) | (flag3 ? Enum.Value3 : 0) -- with pretty formatting for readability, of course, but I can't show that here.
P Daddy
Love Ruby for its use of the question mark on methods that return a boolean: if isSick? goToHospital
Atømix
@P I agree that it's cool and looks neat, but I also guarantee that every time you use it you're costing your company money. Maybe just a few seconds when someone hits it, but it's extremely easy to code that more clearly without the ?: operator no matter how much logical sense it makes.
Bill K
Every time I have to read 4 lines that should have been 1 my company loses money. It makes that much more logical sense to me, and its is quite difficult to code more clearly. Of course, this only applies when the ternary condition and values are relatively short.
Jimmy
I think writing it as "y = x ? x.getParam() : 0" is FAR more readable (lagnuage of choice permitting) and the benefit of viewing between 3 and 7 (depending on brace style) more lines of code on screen makes it a definite win.
Bobby Jack
I agree. For many of us, reading ?: is as easy--I won't go so far as to say I'm incapable of instantly recognizing a 3-line if statement but but maybe I've been programming longer, so for me it takes about the same time. For some others ?: takes minutes--sometimes minutes of my time to explain it.
Bill K
A: 

I too suffer from a OCD when it comes to code format. I'm with Steve, tabbing out your properties is the way to go.

var myObj = {
    anInt: 3993,
    aFunction: function() {alert('woot');},
    aString: "Random",
    aBool: false
}

That hurts me a little. Some may not like it, but this makes me feel much better:

var myObj = {
    anInt:      3993,
    aBool:      false,
    aString:    "Random",

    aFunction:  function() {
                    alert('woot');
                }
}

The way I see it is if I'm spending a lot of time in a certain section of code, I would prefer it not bother my visual sensibilities and distract me from the task at hand. Plus, I think it gives the code a neat and professional touch that helps expedite future enhancements.

jckeyes
Rule of thumb: use tabs to indent; use spaces to align. That way if somebody else loads up your code and they use a different tab width, the indentation will be correct (to them) and the aligned columns will still be aligned.
P Daddy
Thanks, a helpful tip. I supposed I used the term "tabbed" a little to loosely. :)
jckeyes
+1  A: 

Your example should have been:

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

Following the width of the name and not the overall line width. ;)

But, yeah, you're crazy. :P

BoltBait
A: 

I do the numerical comparison thing too as it looks more mathematical to me and it's easier for me to visualise it like a number line.

Some of your idiosyncratic style will be non-optimised though. For example if you were to arrange the cases in a switch statement according to number of statements in a case, you won't be able to optimise it by putting the more likely cases at the top.

I don't do web programming but I guess it's okay to rearrange the css code the way you did as the order in which they appear shouldn't matter? Order of execution matters in non-web programming though, have to be careful about the side effects when rearranging statements.

blizpasta
The order of CSS does matter. Consider this: margin: 0; margin-top:10px;
Liam
Ah, now I know. Thanks. (:
blizpasta
+2  A: 

I like my code to be pretty too, but not where it interferes with readability.

I prefer to put "happy path" first in an if statement, followed by exception paths. If I expect a certain path to happen more frequently than others, it goes first. It doesn't need to be a "positive" condition as krosenvold prefers. This way, it reads like my use cases.

(blizpasta beat me to the punch with the happy-path preceding exception paths. He mentions optimization where I purposely avoided it... I prefer my code pretty and readable. Optimization comes last.)

And in CSS, I prefer "structural" or layout attributes first so I can quickly see where something is going to end up, and only then what it's going to look like. I would reorganize your first CSS example to look like your second, but for my reasons - not yours. :)

Jamie Hale
As an additional step I will actually change the name of the conditional to make sure my "main" case comes first. So "insufficientCredit" would become "sufficientCredit". But never ! it
krosenvold
A: 

There is normally no harm in making it look "pretty", but as in most things use moderation. For example I would prefer to keep items in same order each time with like items group together instead of sorting them. Aligning the operators and values are fine, but don't change the order.

As for "if" statement. I always put the expect out come first and the exceptional out come last.

Jim C
+2  A: 

Many things are contextual for me.

Space or not to space...

   puts "ragu"+"pattabi"  
   puts "ragu " +"pattabi"
   puts "ragu " + " pattabi"

How much to fold...

hr = my_intf->do_the_thing_with( i_1,
                                 i_2,
                                 i_3 );

hr = my_intf->do_the_thing_with( "enter_the_dragon", 1965,
                                 "return_of_the_dragon", 1972 );

hr = my_intf->do_the_thing_with( "enter_the_dragon", "bruce lee", "chinese" );

I 'had to' make a lot of decisions like these when I code. It helps mostly, but my mind won't let me more forward without getting these right. I am recovering :-)

ragu.pattabi
A: 

I think it is absolutely necessary for good code to look good and be well commented. I can't stand it when people ask me to debug code with no structure.

Nick
+1  A: 

Code should be styled to be readable, maintainable, and the order consistent. Personally, I find code with arbitrary spacing to be hard to read. Why force the reader to scan the code across the screen/page to put the pieces of the statement together? The order of code blocks in statement should be positioned in order of logic, readability, and sometimes adjusted for optimization. Unnecessarily spacing things out is a waste of time, and makes the code harder to read, not easier. Hasn't anyone read McConnell?

pro3carp3
A: 

I prefer keeping the formatting style simple. Indent on blocks, and order by logic/optimization. I use the formatter of the IDE (at least in Visual Studio, Eclipse, and Netbeans) With CSS, however, one line for each style with indented children:

#header {}
  #header h1 {}
  #header h2 {}

#nav {}
  #nav ul {}
  #nav li {}
    #nav li a {}
    #nav li a:hover {}

#content {}
  #content p {}

#footer {}


class A {

  private int b = 3;
  private int c = 2;

  public void method(string str) {

     if(str != null && str.length > 5) 
         DoStuffWithString();
     else 
         ShowInvalidError();

  }
}
Steve Tranby
A: 

One small stylistic quirk that actually lends a hand in ensuring correctness is to put any constants on the left side of an if check. This completely prevents the accidental use of assignment-equals instead of comparison-equals.

Saying

if (3.14159 == foo) {
//Do stuff
}

may look a bit strange, but one gets a compiler error in the event that one tries to change the value of pi with

if (3.14159 = foo) {  //No good.
//Do stuff
}
Omniwombat
many compilers now warn you if you use = inside a conditional. I personally prefer the variable on the left because putting the constant before the variable is the equivalent of Yoda-speak: "3 apples I have"? no thanks.
Jimmy
+1  A: 

In a way I am. But I am more into minimizing. Css is definitely my example. It is too long to add here but basically, I alph-order it all.

Why?

Because I have to do changes on the fly a lot more than I want to. Alpha ordering everything in there allows me to just scroll fast and get to what needs the change all in one grouping as opposed to using search and finding it everywhere.

It may be nano seconds to you all but it saves me a lot of frustration and time lost later.

A: 

Pretty for me is readable.

       int anInt    = 10;
     float aFloat   = 1.2155;
MyOwnClass myObject = null;

looks beautiful but it is a pain to read such a code after sometime. And adding new variables is a pain in this case.

I stop with

int anInteger = 10;
float aFloat = 1.2155;
MyOwnClass myObject = null;

My obsessions are: a space before and after comparison operators and a new line before a opening brace (It is strange for why people don't use this way and prefer the opening-brace-on-the-same-line approach).

Nivas
A: 

I don't tab align, but whenever I'm declaring a bunch of one thing (Such as ints) instead of something like:

int num = 5, num2 = 7, num3;

I like to arrange it so that any variable with an initial value (Like num2, and no, my lingo is not so good) goes last, and if there's more than one then arrange by size (Or alphabetically or whatever):

int num3, num = 5, num2 = 7;

Along with that, I really hate the function() { convention. I prefer:

function()
{
    // Code here.
}

It just looks neater and easier to read to me.

Peter C.
A: 

The alignment of the parameters vertically looks nice, yet it for me it detracts me from scanning across the declaration as a statement.

I've cut and paste a snippet of me in full obsessiveness :

public static String intArrayToString( final int[] array ) {

    if ( array.length == 0 ) {

        return "[]" ;
    }

    StringBuffer sb = new StringBuffer() ;

    sb.append( "[ " ).append( array[ 0 ] ) ;

    if ( array.length > 1 ) {

        for ( int i = 1 ; i < array.length ; i++ ) {

            sb.append( ", " ).append( array[ i ] ) ;
        }
    }
    return sb.append( " ]" ).toString() ;
}

Lots of spacing : this is due to writing alot of example code, and is a rollover from writing purely for readability.

I would hope your second example's form is the norm, I was taught at varsity to write these comparisons as if they were on a numberline :

if ( 0 < n && n < 10 ) {

    doSomething() ;
}

And as for the last example, I would omit the boolean comparison. A true case then a false :

if ( afflicted ) {

    doSomething() ;

} else {

    doSomethingElse() ;
}
_ande_turner_
A: 

I know that I will read that code probably close to 15 times before it is placed into production. Spending time in formatting the code, perhaps looks like I am only making the code look pretty, but for me, it gives my mind a couple of seconds to think through the code, before I move on to the next bit.

Code that is not structured neatly and consistently is a warning to me, that the developer did not understand the problem enough, to show his intentions clearly, or the developer that did that code just did not care. I would rather not work with such an individual if I have a choice. I believe it is Steve McConnell who said, that the compiler does not really car how the code looks, but it is a mechanism for us humans, to work within the confines and limitations of brain.

Any person can write code that looks complex. But it takes a great developer to take a complex piece of code and turn it into something that everybody points to it and say, oh yes that is easy and simple to understand.

Rihan Meij
A: 

How about alphabetical order

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

I prefer brackets on their own line

If (a)
{
}

instead of

if (a) {
}

but now that C# has Auto-Implemented Properties I find myself fighting my own auto-matic code formatting rules.

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

}
Todd Smith
A: 

I'm not qualified to assess your neuroses, but I can tell you that I am often found writing in this style:

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

I like some of the other things that you do, but I am not religious about any of them. It really depends on the context and what seems most important to have stand out and/or be easy to grasp.

I must admit that I never need to look at diffs (and I don't use debuggers either), so I am not ashamed to reformat the appearance on a revision, adjusting to have the changes blend into the preserved style.

orcmid
+2  A: 

For me, writing readable code is best. No matter how the format is, as long as it is readable for other programmers when/if they take over programming, it is pretty.

And always have comments.

Thorpe Obazee
A: 

The one thing that I vary with on the original post would be the conditional. I don't look as a conditional as a matter of styling preference, but rather a logical one. The most common case would be the first case, and would progress to the least common case. Applies to both if statements and switch statements in my code.

joseph.ferris
A: 

Many people mentioned that diff tools will show unnecessary diffs if you try to format your code manually. However, good diff tools ignore whitespaces, so this is not an issue.

A more important point is that code written by a person is meant to be read by a person. Therefore, try to make it as readable as possible. If additional whitepsaces can clarify your code, then do it. Most whitespaces are used for readability anyway. For example, indentation is purely aesthetic is most languages.

Martin Cote
A: 

I like to make sure there's adequate spacing between lines of code, and I have comments that explain things. That's about the extent of my tidying up.

In Visual Studio, I use Ctrl+K then Ctrl+D (Autoformat code) judiciously to have everything aligned/spaced properly. I'm not as OCD as you, though :)

Matt S
+1  A: 

Alphabetical ordering scales better; its benefit in a complex CSS file is much greater than in a small file.

Liam