Do you try to make your code look pretty? [closed]
Asked Answered
D

34

30

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?

Detector answered 14/11, 2008 at 17:36 Comment(15)
if (0 < n < 10) :)Usanis
if 0 < n < 10: It works in Python.Humfried
@Scott: make it a community wiki post (due to the post is a poll-like).Humfried
judging from the responses below, you are not alone. But i wonder, do people for code-formatting OCD ever actually complete a project?Besotted
@[J.F. Sebastian]: i disagree, there is no need for this to be a wiki post, it is a legitimate question asking for subjective opinions, not a voting pollBesotted
I'm pretty sure even Python evaluates "n < 10" first, then takes the "true/false > 0". So, the expression as given actually works, but not for the reason a reader is likely to guess. So good luck changing it without breaking it!Supererogatory
@[Steven A. Lowe] According to the FAQ, "legitimate question" and "asking for subjective opinions" are disjunct. Making it a wiki is a fair-enough compromise.Mims
I'm shocked that this is not the only question to have the tag "pretty-print"Allen
I used to care about stuff like this, up until I discovered it took a lot of work to maintain, and it would fail to diff nicely.Ouster
@Tomalak: I see no such info in the FAQ stackoverflow.com/faq; this post satisfies the first paragraph's requirements. It also satisfies the se of the subjective tag here #19057 - what's your faq link? thx!Besotted
One line CSS rules ftw!Lentissimo
@sep332: python does it correctly.Eddi
Pretty code does not verbosely evaluate boolean expressions! They should be /if (afflicted)/ and /if (!afflicted)!/Gerhart
While I don't agree with all of your examples, I think it is a really good question. Although it can be taken too far, I think "pretty" code is often better code.Welles
only thing that i try is use "ctrl + k & ctrl + c" in Visual Studio Code Editor!Merell
O
75

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
Ouster answered 14/11, 2008 at 17:36 Comment(13)
I completely agree here. This is very important to note!!Huntsman
If you're using a sane diff tool like DiffMerge, you can tell it to ignore "unimportant" differences like whitespace.Stemma
But does it handle white spaces between identifiers on the same line?Ouster
Yep. I'll try to post a screen shot.Stemma
We should change the diff tool to be more useful to us. Its machines that work for us, not the opposite.Vikki
True machines should work for us, and thus we shouldn't modify formatting by hand either.Growth
DiffMerge, showing unimportant differences (note differences in highlighting): img185.imageshack.us/img185/5351/withunimportantdifferenue8.png DiffMerge, not showing unimportant differences: img185.imageshack.us/img185/8641/withoutunimportantdiffedk2.pngStemma
Beyond Compare also handles this nicely.Wadai
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 pastie.org/315160Nicotiana
I completely disagree. Code written manually is meant to be read by humans, not machine. Thus, it should be as readable as possible.Pinkston
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.Pekingese
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."Jorry
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.Blink
L
23

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.

Lampedusa answered 14/11, 2008 at 17:36 Comment(5)
Don't every try to use asterisks in an answer.Lampedusa
Why no astericks?Gard
Try it and you'll see. I had to edit my post 10 times just to get bat**** to show up right.Lampedusa
+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.)Welles
Oh, is that what he was going for? I was trying to figure out his reordering logic...Languedoc
B
20

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

if (afflicted) {
    GetSome();
    HelpRight();
} else {
    NowPlease();
}
Boater answered 14/11, 2008 at 17:36 Comment(5)
yeah but but .. that will almost Always put dangling little whimpy else-blocks in your code, no?Detector
MOdified slightly to only pertain to if-else statements ;)Boater
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.Ardent
@Bryan; I normally prefer to exit the method for whimpy blocks. Or extract method for the beefy one.Boater
My take on it is that you should always test for exceptions, never the normal case, #114842.Deadpan
P
16

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();
}
Pale answered 14/11, 2008 at 17:36 Comment(1)
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.Stomatal
E
10

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";
            }
Enterogastrone answered 14/11, 2008 at 17:36 Comment(8)
:) .. yeah but .. hmm, i dunno .. that 'border' line looks out of place hmm ..Detector
This looks a lot like my CSS!Supererogatory
i don't like those hanging braces, seems sloppy/unbalanced...Besotted
tabbing properties is the way to go!Buss
I go alphabetical, left to right...Artur
Pretty yes, easy to maintain NO. Your diff would also end up showing changes on lines where only the formatting changed.Ouster
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.Guanabara
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.Thyestes
B
9

it should be

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

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

Besotted answered 14/11, 2008 at 17:36 Comment(7)
LOL. However, I do think "if (afflicted == false)" is prettier than "if (!afflicted)", but that's my inner VB talking.Lampedusa
@MusiGenesis: you should see an exorcist about that inner VB thingy, sounds painful!Besotted
ugh! comparing a boolean value to true/false makes me cringe! If it's in code I have to maintain, it makes me angry.Treed
@MusiGenesis: In VB: "If Not afflicted Then ..."Wadai
@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";Wadai
@P Daddy: And please use parentheses!Liquidambar
@Ferdinand Beyer: Please learn operator precedence order.Wadai
S
5

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.

Scammony answered 14/11, 2008 at 17:36 Comment(10)
Call me crazy, but I actually find "y = x == null ? 0 : x.getParam();" easier to read than the if/else block.Treed
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?Scammony
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.Wadai
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.Scammony
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.Wadai
Love Ruby for its use of the question mark on methods that return a boolean: if isSick? goToHospitalTram
@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.Scammony
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.Holmes
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.Burtis
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.Scammony
S
3

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.

Sotos answered 14/11, 2008 at 17:36 Comment(0)
L
2

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.

Lodie answered 14/11, 2008 at 17:36 Comment(0)
N
2

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

Nicotiana answered 14/11, 2008 at 17:36 Comment(0)
M
2

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. :)

Mir answered 14/11, 2008 at 17:36 Comment(1)
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 ! itBoater
P
2

You're not alone :-) I use often the alignment practice (like in Steve's answer):

foo     = egg     + spam
foobar  = sausage + spam

The easier to read, the better.

Another little thing I try to do systematically is to group the terms in an expression according to operator precedence, i.e.

if (a<b && c<d) ...
x = a*b + c*d

instead of

if (a < b && c < d) ...
x = a*b+c*d
Paint answered 14/11, 2008 at 17:36 Comment(3)
diffs will fail with changing alignment of codeOuster
You can easily ignore white space in diffs. -iwSardanapalus
@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.Pekingese
A
2

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.

Allen answered 14/11, 2008 at 17:36 Comment(0)
E
1

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

Ergener answered 14/11, 2008 at 17:36 Comment(0)
P
1

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.

Petrina answered 14/11, 2008 at 17:36 Comment(0)
K
1

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?

Kc answered 14/11, 2008 at 17:36 Comment(0)
B
1

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

Boni answered 14/11, 2008 at 17:36 Comment(0)
R
1

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.

Reiners answered 14/11, 2008 at 17:36 Comment(0)
F
1

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.

Frida answered 14/11, 2008 at 17:36 Comment(0)
P
0

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

Persephone answered 14/11, 2008 at 17:36 Comment(0)
P
0

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.

Pinkston answered 14/11, 2008 at 17:36 Comment(0)
T
0

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.

Thyestes answered 14/11, 2008 at 17:36 Comment(0)
S
0

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.

Solemnity answered 14/11, 2008 at 17:36 Comment(0)
C
0

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() ;
}
Competitor answered 14/11, 2008 at 17:36 Comment(0)
S
0

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

Staurolite answered 14/11, 2008 at 17:36 Comment(0)
G
0

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();

  }
}
Growth answered 14/11, 2008 at 17:36 Comment(0)
Z
0

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.

Zr answered 14/11, 2008 at 17:36 Comment(0)
E
0

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.

Einberger answered 14/11, 2008 at 17:36 Comment(0)
I
0

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.

Inwrap answered 14/11, 2008 at 17:36 Comment(1)
The order of CSS does matter. Consider this: margin: 0; margin-top:10px;Ergener
B
0

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.

Buss answered 14/11, 2008 at 17:36 Comment(2)
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.Wadai
Thanks, a helpful tip. I supposed I used the term "tabbed" a little to loosely. :)Buss
L
-1

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.

Liaison answered 14/11, 2008 at 17:36 Comment(0)
D
-1

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.

Dresser answered 14/11, 2008 at 17:36 Comment(0)
A
-2

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; }

}
Aeschines answered 14/11, 2008 at 17:36 Comment(0)
A
-2

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
}
Aurelio answered 14/11, 2008 at 17:36 Comment(2)
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.Holmes
I'm in agreement with Jimmy. And in those cases where you intentionally put an assignment inside a conditional, you enclose it in an extra set of parentheses to silence the compiler warning and make it obvious to the reader that it was intentional.Weswesa

© 2022 - 2024 — McMap. All rights reserved.