Stack OverflowWhat is the most frustrating programming style you've encountered?
[+233] [148] JaredPar
[2008-10-26 08:08:51]
[ coding-style ]

When it comes to coding style I'm a pretty relaxed programmer. I'm not firmly dug into a particular coding style. I'd prefer a consistent overall style in a large code base, but I'm not going to sweat every little detail of how the code is formatted.

Still there are some coding styles that drive me crazy. No matter what I can't look at examples of these styles without reaching for a Vim buffer to "fix" the "problem". I can't help it. It's not even wrong, I just can't look at it for some reason.

For instance the following comment style almost completely prevents me from actually being able to read the code.

if (someConditional) 
// Comment goes here
  other code

What's the most frustrating style you've encountered?

(58) This should be a community wiki before it's reopened. Getting rep for having an opinion on best/worst type questions is inconsistent with the intent of the reputation system. - tvanfosson
I agree. Is that something only the owner can do? - Mitch Wheat
Change title to "Frustrating programming styles you've encountered" so that people will add things that they've encountered that are not necessarily the most frustrating for them. Thus it will be more like a wiki of bad style. - Ates Goral
(23) Please, no accepted answers for poll questions. I want to see the highest voted answer on top, not the one some single person likes best. - Fabian Steeg
(5) You know, I noticed that there is not a single response (as of now) that uses Haskell as the language with ugliness in it. There could be a good reason for that. - Robert Massaioli
(15) I will make a similar argument for INTERCAL. - Kevin Panko
(1) @Robert Massaioli, yes there is. It's because nobody who makes up programming standards like this knows what Haskell is :P - jdizzle
[+430] [2008-10-26 20:00:48] CAdaker

For a basic university course in programming, we were supposed to write a simple client program connecting to a server. Here is a part of the server code we were given, written by someone who obviously really, REALLY prefers python's syntax to Java's.

It was only about 50 lines in total, so it's really no big deal, and we didn't have to do anything with it except run it. But the style still bothers me.

import*                                         ;
import*                                          ;
import java.util.*                                        ;
public class Server                                       { 
    public static void main( String[] args)               {
        try                                               {
            ServerSocket sock = new ServerSocket(4712,100);
            while(true) new Handler(sock.accept()).start();}
        catch(IOException e) {System.err.println(e);}     ;}} 

class Handler extends Thread                              {
    public void run()                                     {
        Random random=new Random()                        ;
        try                                               {
            //yada yada yada
        catch(Exception e) {System.err.println(e);}       ;}}

(7) Holy crap, I'd kill whoever did that. - FlySwat
Nah, I think it was more or less meant as a bit of a joke. And it was obviously NOT taught as Java coding guidelines. - CAdaker
(1) Rather funny actually... Looks like Python, if you hide the right part! ;-) - PhiLho
This seems like it'd be a pain to keep the right columns lined up when editing code, though. - Cristián Romo
(163) It hurts my eyes. - Mike Powell
(6) I can almost hear the guy that wrote this "See, look at this ugly Java code, Python is clearly superior" - MattBelanger
It seems like old langages (Cobol, Fortran) - Luc M
(1) Funny. That code actually looks clean if you ignore the right part. It looks python-y ;-) - Joachim Sauer
(1) You could use align-regexp in emacs to align the braces . . . okay, this is awful! - JasonFruit
(44) amazingly, it was a pleasure to read! although I would guess a pain to write while maintaining the vertical line to the right! - hasen j
(2) I would actually praise the programmer if he actually write a converter from his style to real compilable java code. - Hao Wooi Lim
oh... my... goodness... - SnOrfus
(3) I really hope the guy writing this was drunk or has some other excuse. This is one of the most perverted things i've ever seen. - mafutrct
(1) Quick, run it through a pretty printer! - Ian Terrell
(5) This is why eclipse has Ctrl + Shift + F. Fixes bad markup in a single click. - Marius
(2) I don't like eclipse formatting style. I prefer braces on a new line ;) - Ikke
(106) Wow. I've never seen such beatiful java code. - Rob Lachlan
(2) Sweet Gorilla of Manila, that's awful! - John McCollum
@Ikke: Luckily, it's configurable ;) - Adam Jaskiewicz
(5) Wow. That's so painful I'm tempted to flag this answer as offensive. - David
(4) That is the stupidest thing I've ever seen - Andy White
Shame not all curly braces are neatly aligned. ;-) - Gamecat
(42) Reminds me of winter when the plow trucks come through and push all the snow to the side of the road :) That's a very interesting coding style. One could really mess with coworkers' heads, especially if one moved the column of scope operators far off to the right. "What? C#? How does this compile?" - Triynko
(125) This is plain awesome, that's what it is (I love python). Whoever whote this code should be given a medal. Posthumously, of course. - shylent
(1) Oh... my... god... - kastermester
(1) Ours is like that, except it's EVERY brace, bracket, parentheses, and parameter lined up on its own tab boundary. I can't read it without stretching VS over both monitors. What's worse is that some of the parameters are lists of 1s and 0s laid out in a grid with a header above them. Supposedly it's much easier to read than using an enum. God help me if ReSharper formats any of those files and I check them in. Thankfully, they're in a project I don't touch. - Chris Doggett
(1) I hate Python style. - Isaac Waller
(2) @Marius: "Ctrl + Shift + F" ... "single click"... head asplodes... - fretje
(1) Haha, this is awesome. I've seen that before. We apparently study at the same uni! - Daniel
(3) That it tremendously horrid! - johnc
(1) I lol'd irl when I saw that. - Charles
(1) reading this even hurt my feet! - Shaharyar
(9) reading all these comments is almost as amusing as looking at this code. haha =) - user176121
(1) Haha, that's freakin awesome :D - AndiDog
now thats what you call hardcore - Dal
(1) OMG!!!!!!!!!!! And after all that nitpickingly enforcing of an absurd coding-style, this guy even collapses all the closing braces in the last line of a block. OMFG... - Frunsi
that's just wrong - mcgrailm
(4) ...That is how you know that Java has way too much Syntactic cruft. - Robert Massaioli
(1) This just made me laugh so hard, did this guy work for dotfuscator? I would feel a ctrl + k + f coming on. - Steve Sheldon
(1) If Python caused brain damage, this is what it would look like. o.O - Ben Blank
Wow, actually I would like that for C#... whitespace sensitivity, right? That would be something. I'd use it instantly. - Turing Complete
W. T. F. ....... - Skilldrick
you could have fun with this in a java would get killed in a code review though - Anthony
(1) you yada, yada, yadaed over the best part - Kyle
Any reasonable compiler should be able to infer the code given the braces and semicolons. - Joey Adams
Heh. Recently reviewed project with this formatting style. People actually do this. - Arnis L.
in Eclipse i'd Ctl Alt F that crap haha - Kenny Cason
[+336] [2008-10-26 09:31:52] peterchen [ACCEPTED]

Interestingly enough, that's

if (0 == foo()) {}

i.e. putting the constant on the left to avoid an == / = mixup. I know it would be better to do it, and I feel bad for it, but reading it is for me a mental speedbump.

Doesn't say much except that being annoying doesn't mean it's necessarily bad.

(55) This used to be strongly encouraged if you were working in C or C++. It saves you from a nasty bug that the compiler will joyfully allow. Nowadays any static analysis tool will alert you if you use = instead of ==. - Bill the Lizard
(20) Any sane compiler can warning you as well. - JesperE
(44) "Mental speedbump". I like that analogy. - JesperE
I find it annoying too, and what about the uglier cousin "if (0 < bar) {}" ? - Sklivvz
(2) That’s perfectly fine for me, I… sort of picture the real axis and find the bar to the right from the zero. Apparently these things are highly subjective. - zoul
I model it as a comparison of two items in my mind. It really doesn't matter where the constant falls. It becomes natural after a bit, anyway. - David Grant
(8) Hillarious. I personally love that style but it's great to see other people have rational styles they can't handle either. - JaredPar
(1) Like zoul, I like (0 < bar) for visualizability. It grows on you (e.g. here's how you tell if x is between a and b: a < x && x < b) and 0 == foo becomes no problem either. - Darius Bacon
Yes, it does irritate a little, but I would not blame anyone for doing this. It's somewaht like blaming a war veteran for scars. No, I cannot agree that this is one of those things that drives me crazy. Not even close... - Yarik
I wouldn't blame anyone - far from that. I guess the frustration stems from knowing it would be better, but my "code parser" still does not accept it after so many years. I am surprised that it made the list that high. - peterchen
I know the feeling. It should've been high on a poll like "Most frustrating compiler deficiency", but not on "Most frustrating coding style". :-) - Yarik
(2) I, for one, really like the formatting of "if (0 == x)". Generally, I already know by context that the if-statement is referring to variable X. The only question is what value is it checking for. Hence, I read it as "if ([important value]...)" where the rest is implied by context. - abelenky
(1) @Skliwz: I find (0 < bar) uglier, too. I read it as "when zero is less than bar -- unless of course hell freezes over and the value of zero changes." - Ates Goral
(3) It's interesting how many 'frustrating' programming styles, like say excessive Hungarian notation, are all based around the need to compensate for "shotgun pointed at foot by default" behavoirs in C/C++. - David
@David... with a hair trigger! - Software Monkey
Constants always go on the left. - Thomas L Holaday
(2) Ew I too hate this. It's like, "Hm, I can either not be silly and remember to put == [not difficult], or I can just throw everyone else off and put the constant on the left, just because I can't remember not to use =" - GMan
(6) Alternatively it's like thinking, I can just remember not to crash or I can ruin my hair and wear a crash helmet. - Martin Beckett
(14) Thomas, yes, as in "int 1 = x;" - jmucchiello
(9) Hate it. It doesn't read like English: "if zero is (the result of) call foo()", instead of "if call foo() is zero". - Loadmaster
(1) Agreed. For readability, the subject of a comparison should be read first. This immediately establishes the importance of each subject in an expression or phrase, regardless if its code or not. It's like saying "An ewok looks like your teddy bear." - Nick Bedford
And here I thought this idiom came from Bourne Shell: if [ 0 == $x ]; then ... fi. You put the constant first because if you did it the other way it would halt the script or perform an invalid test if $x was empty (thus omitting the parameter to [). - Mike DeSimone
(79) I call this the Yoda programming style. "hmrrrmmm if 0 is foo() on go you". - Thomas
(1) The reason is clear, but I find this style nasty too. Though I thought I would never ever fall into the = instead of == trap. But you know what? Last week it happened, I double-checked code and repository to make sure that it was me myself and I to type the =. And yes, it was me, and instantly I remembed this idiom. So, I really do not know whether it is good or not, but in a few situations it may help. So I cannot give +1 and I even cannot give -1. I really have no idea :D - Frunsi
This was called "Yoda conditions" in the "Programming jargon you coined" CW. - dreamlax
(4) What's really frustrating is seeing someone give this advice... for a language like C# without implicit casts. facepalm - MiffTheFox
(2) I can't stand this. It's hard to read and is just unnatural. And really, how often do you make this mistake? For me, it's not often enough to put up with having to twist it around just to read it correctly. Think of it as a speed bump for the brain. - kirk.burleson
(1) There is no way it should be allowed to write foo() = 0. What is that supposed to mean? - Thomas Ahle
(2) @Thomas Ahle: This is valid C++ if foo returns a non-const refernece. - Philipp
(1) In C# this pattern can also make sense for comparing values. Let o be a variable of type object. if (o == 4) {} is not allowed; if (o.Equals(4)) {} throws an exception when o is null; but if (4.Equals(o)) {} works perfectly fine. - Heinzi
@frunsi: maybe it's frustrating because sometimes it does help? - peterchen
Don't forget its use in PHP, where there are no static analysis tools to save you - amindfv
[+289] [2008-12-31 00:09:23] Dave Ray

Explicitly testing against boolean literals:

if(foo == true)

and (Joel Spolsky mentioned this on the podcast) refusing to return boolean expressions:

if(x < 24)
    return true;
    return false;

that makes me crazy.

(37) I don't see why this is bad. If they do it this way and commented it well, I would just assume the programmar wanted clarity and not desperately saving a few lines of code. - Hao Wooi Lim
This! I actually have a buddy who checks for thing == true/false/1/0 all the time. His return statements are some long multi-if statement thing, too. - Nick Presta
(3) @Hao: because ignoring (or feigning to ignore) that an expression can return a boolean type and not using this capability is laziness (or worse). I am not fan of super conciseness, on the contrary, but extra parentheses and above examples makes me cringe. - PhiLho
(61) Damn. We say "if it's raining, open your umbrella" and NEVER "if it's true that it's raining, take your umbrella"... Testing explicitely against boolean is as verbose and as un-natural as the second example - Johan Buret
(106) It's outright retarded. It says "I do not understand expression evaluation". To think this is in any way a matter of clarity is an insult to the reader. - annakata
When I started my career, the senior dev I worked under used to go mental over this one. Now whenever I see this, I always have a bit of a smile. - Stephen Newman
(50) Clarity?! What is unclear about "return x < 24;" ? Totally +1 on hatred factor - flq
(6) I find this usually is caused by code cruft. There may at one time have been stuff before the returns and then it got removed and the big if-else remains. - jmucchiello
(7) In some languages, there are multiple possible true values, and "true" can only be one of them. In those languages, "x == true" can be false while x is true. The practice is not only stupid, it's dangerous. - David Thornley
(19) @David Conversely, sometimes you do want to explicitly check against a boolean. For example in Javascript it's typical for callbacks to return explicit false to suppress the default behaviour, whereas not returning a value (the return value is undefined) should not suppress it. - Kieron
Since undefined would normally evaluate to the same as false, you have to use the non-type-coercing operators to explicitly check against the boolean, eg if (val !== false) { ... } - Kieron
(1) Some C++ compilers issue a warning when automatically converting an integer expression to boolean as in "int t = 0; if (t){}", usually saying "possible loss of data converting int to bool". I think some of the devs in my shop have gotten used to doing "== true" just to avoid those warnings. - veefu
(3) return x < 24 ? true : false; - Kevin Panko
(1) David...what languages are you talking about? - Kyralessa
(1) In lua, the default test (if foo then ... end) checks if foo is not false or nil. This alone is a good incentive to have explicit boolean checks in most cases. - RCIX
I like doing this sorta thing (random code example) :P if ((myObj = makeSomeObj())) { myObj.doStuff() } - Nick Bedford
(4) I think (a == true) is unnecesary, however (a == false) is much more readable that (!a), and it's language agnostic (some languages don't support the ! operator). - Max Toro
(9) Honestly I sometimes write code like that (the second example). Mainly because it makes it easy to put a breakpoint on the "return false" line (easier than conditional breakpoints). Or add a debug-message or assert later. - vobject
(5) In C++, some debuggers are horrible. Putting a conditional breakpoint that stops when ( x < 24 ) evaluates to true can really slow down a program. It is far easier to simply put a break point on the return true. I understand the use of this syntax in environments like that. Not otherwise. - carleeto
(1) I hate these so much... 8 physical SLOC vs 1! - Jake Petroules
(2) I call it clarity, my lead calls it fluff. I have no problem reading it either way, but these days I try to code so anyone can read it. It's just a few more keystrokes! - kirk.burleson
What if foo was a nullable boolean? I thought you can't do if(foo), you have to do if(foo == true). - Kezzer
(2) if not IDontUnderstandBooleanAlgebra() = true then return false else return true - Christian Hayter
@Kezzer: you could do this if (foo.GetValueOrDefault()) check - VoodooChild
(2) What drives me even crazier is: if (x < 24) { return true; } else if (x >=24) { return false; } - Ates Goral
[+271] [2008-10-26 15:35:54] Antonio

Useless comments.


i++; // Increment of i

(81) at least it didn't say "by 1" - benPearce
uhm, are there really people who code like that??? - hasen j
(3) I used to - simply to aid the reader of my code if they were new to the particular language I was writing in. If you're reading along and you don't know what "i++" does, it can help to have a comment. - Dalin Seivewright
(12) @Dalin If you're writing a very basic tutorial/book, sure. If you're doing absolutely ANYTHING else, it's completely redundant. People reading your code are likely going to be at least slightly familiar with the language. If a keyword or operator is unfamiliar, - Stuart Branham
Classic rookie commenting style! - Richard Ev
(108) /* Yea, and God said to Abraham, you shall increment the value by one. One being greater than zero yet less than two. After incrementing, thou shalt then emit the original value. The original value being one -- not zero nor two -- less than the new value. */ - Tyson
This one is the cousin of "i += 1;" - MusiGenesis
(3) +1 i hate it when ppl do that too - user176121
(1) @Tyson You forgot to mention it is an integer :P - luiscubal
hahahahaha funny - Enrique
(1) usefulness_counter++; // increment usefulness_counter of 1 or in plain english: up-vote the answer - Frunsi
I once saw the comment (as a joke, I hope): // Neat trick to increment i by 1. - dreamlax
(2) (This comment is a useless one.) - Kevin Panko
(2) @Stuart - i++; // ;) - MiffTheFox
I don't do this, but it doesn't bother me either. I never understood why people get bent out of shape about any kind of comment. Don't read it if you don't like the style. I find too many programmers think they write self documenting code and I would rather see them writing these comments than none at all. - kirk.burleson
(1) +1 // increment score by one - Brendan Long
(1) I don't know, it doesn't bother me all that much. I sometimes write out all my thoughts in comments while programming which at times causes such obvious comments at certain lines, just to keep my thought process down somewhere. This particularly happens when I'm debugging some really complex code in an attempt to make it simpler. - The Jug
vote++; // upvote - Christian Hayter
Worth it if you're doing something haxy though. IE, if incrementing it by one will have some wierd side effect (like if you've hooked the setter method of an object or somesuch) - Richo
[+257] [2008-10-26 12:02:54] Yarik

Omission of braces just because they are not required for single-statement blocks. Like this:

if (SomeCondition)

If you spent enough time staring at code like this

while (SomeCondition)

and wondering "is this a bug or just somebody's sloppy indentation?", then I bet you know what I mean. If you didn't... well, I guess you were just lucky so far. :-)

(2) Man, this one drives me up the wall! - Gary Willoughby
(9) It really bugs me when folks bracket single-line blocks... - Shog9
(55) That’s interesting, I’m glad I am allowed to do that (even in for or while loops), the extra braces look ugly to me. - zoul
(35) It's less offensive if it's all on the same line, rather than split on two lines. - neonski
(31) braces helps when you change your mind and add a few more lines. - artificialidiot
(128) Completely disagree. One liners are much nicer looking without the braces. - JTA
(12) Nice or not nice - that's quite subjective. Consistency (like using braces always) has some beauty to it too. :-) But time-bomb is a time-bomb. When it blows up - it just does not help that it looked nice! - Yarik
(8) Braces tell me: Do these THINGS (plural)... no braces tell me instantly: do ONE thing. I remove braces when not necessary. The braces are meant to GROUP. If there's one instruction, they're redundant. It's silly to add braces just in case you add another method. - Atømix
(53) Atomiton: why complicate things? if there are braces around every block, you don't need to think of the rules at all. - Ed S.
(2) Agree with @Ed Swangren. - Mitch Wheat
(9) It seems that the people that like braces around everything won the "readability war" somehow, but I totally hate it. I find one-liners being bracketless infinitely more readable (yes, even when nested.) - PhoenixRedeemer
(1) After using Python, two brackets for one block of code feel like lead shoes. I use them as a precaution, but I still cringe every time. - Nikhil Chelliah
(1) Why don't you add a space inbetween and remove that ident there on DoSomeOtherThing(); - Tim Matthews
(1) This doesn't bother me too much. What I really hate is when people bracket single line blocks the 'long' way (ie. brackets on a single line) turning a 2 line statement into a 4 line statement with no added value. - Nick Presta
(2) Amen to this. I wish new languages would stop perpetuating this. Looking at you C# - annakata
(3) I agree with atomiton: it's redundant. Qualifying that, I will note that I ALWAYS (always) leave a blank line after the one statement. - SnOrfus
When there is any question at all, have your environment reformat your code and see if it moves them. Personally I don't care either way because it's so easily ignored. - Bill K
Don't Repeat Yourself - abababa22
You'd hate me... - Dinah
(17) I'm firmly for always use brackets. It indeed can look ugly (and one of the reasons why I use the less common first { on the same line as the if statement) but I must literally have found hundreds if not thousands of bugs in other peoples code cause by incorrectly assembled unbracketed if's - Cruachan
(1) An automated static checker like PCLint will flag this as 'Suspicious Indentation'. Unfortunately, when a mere human is looking for something like this in 10000 lines of code, they will probably not see it. - mkClark
(2) I prefer to omit the braces for a single-liner, but I usually follow them with a blank line. - Triynko
I omit braces for single lines, but when I do I put the statement on the same line and usually leave a blank line after it. - Joel Coehoorn
(1) I don't get it. I just hit Control-K, Control-D all the time, and Visual Studio automatically fixes the C# indentation for me. So a no-brace if never causes a problem. - Kyralessa
(2) Since white space has no meaning to the compiler in this case I'd opt entirely for including the braces even if it makes it slightly less readable to some. Braces are used to delimit the block so I think being explicit here is a good idea in general since it improves edit-ability. - Jonathon Watney
(1) Come on, people. We're in the 21st century. If you are using an editor that allows you to put wrong indentation like that easily, then you're stuck in the past. Find something that can place your cursor correctly and/or auto-format your code, and upgrade to it. - Timwi
(1) MISRA-C 2004 Rule 14.8 forbids this kind of code (for better maintainability): it says that all bodies of if, else etc must be braced. In my opinion this is a very good thing! Static analysis tools (like PC-Lint) that support MISRA will pick up on this one. - DrAl
(1) Why are people worried about extra braces? If you can't read braces quickly how do you deal with nested ifs and functions? It seems pretty dubious logic to decry braces for readabilities sake when so many language constructs use them anyways. - Ron Warholic
it was actually in a coding standard at my last place of employment to not use braces in a single statement block (though i never followed that rule). this led to many subtle bugs. - dan
The flip side of the coin is all the unneeded braces for a long list of if (cond_n) foo_n(); statements. - Loadmaster
In the book I'm writing, I intentionally write single-liners without braces... because I have to save space on the page. In real programming, the no-brace style makes me see red! - Chip Uni
(2) If you can't read this (no lines sorry): if (condition) foo = bar(); else bar = foo(); then something is wrong. - Nick Bedford
(4) I hate this too. Every time I try to adapt a jQuery or PHP plugin, I find myself going and adding braces for all the stupid parts where they left them out just to make sense of the code base. Even better is one plugin where everywhere they removed braces after Ifs, there was a comment saying 'save a byte'. - flexxy
(2) I happen to find it much more readable. However, I cannot stand when a developer mixes and matches in the same if statement. So you get an if statement does not have braces but the else statement does. - Thomas
(1) This depends a lot on the context. Whenever I read and/or modify code, I have to think in abstractions, and one of the rules that makes up the abstraction is that this world is full of if(cond) do() constructs, where the code structure (style) gives me a clue about do(), but the semantic structure makes it very clear, that do() is a single thing. Of course this requires a strict and consistent code style!! IMHO those brackets are only required if the style is not consistent. - Frunsi
.. so, people falling into the trap of missing brackets in a single-instruction-if-clause just have not understood the coding style, or the code does not obey the given coding style. So after all, those brackets are ugly and superfluous. Bugs resulting from those missing brackets indicates a diffused-coding-style-code-base or a programmer that has not yet adapted to the style of the given project. - Frunsi
This must be the most downvoted answer in this topic.. - Blindy
(1) When I write lines like this I write them as one liners to make the meaning absolutely clear. If it spans multiple lines then it gets braces. - Robert Massaioli
It doesn't bother me to see it, but I don't write code like that anymore either. I found that half the time I ended up adding the braces later when I added more code, so I got in the habit of always using braces. - kirk.burleson
I am forcing myself to write braces, even though they in some cases feel like added visual clutter. I do this mainly because the official java coding conventions say that you must always use braces for if statements. - Alderath
I had an javascript person who did this...he is a much better coder than I am, but this still drove me crazy - Anthony
This really screws me up as I switch between Python (where the second example actually does what it looks like it is doing) and PHP and C++ (where it doesn't) for different programs. - Macha
@Anthony and in JS is especially dangerous, due to semicolon insertion. (at least I think - I'm not a hardcore JS person but I've read D Crockford's essays and talks) - spacemanaki
IDE, autoformat, bind to hotkey, press every couple seconds. - Razor Storm
[+218] [2008-10-26 09:55:46] pablito

The use of type prefix in variables name in modern languages like C#,

int iIndex;
string strMessage;

They enforce this rule at my work... for Java code! Personally, I still use b prefix for booleans (in any language), because that's the only type for which I do if (bVar) (no auto conversion from 0, '', undefined, null, etc. to false). - PhiLho
(18) That's not Hungarian, it's very weak variable name typing. Hungarian is vastly more complex. - Cruachan
(58) That's not Hungarian. Please, please stop bashing Hungarian if you do not understand what it is!! - Yarik
(25) yes it is, please look at the formal definition from wikipedia: "Hungarian notation is a naming convention in computer programming, in which the name of a variable indicates its type or intended use" - pablito
(1) @pablito: Saying strictly, there is no such thing as Hungarian notation. There is Systems Hungarian (what is shown in your example) and Apps Hungarian. If you criticize Systems-H - I am WITH you. But if you criticize both Systems-H and Apps-H, I disagree... - Yarik
@pablito: The current wording of your answer only increases the wide-spread confusion about what Hungarian notation actually is. That is the main reason why I voted your answer down. I would be happy to withdraw my downvote if you made your answer less ambiguous. :-) - Yarik
Ok, just to make things clear I don't criticize Hungarian notation, I think in langages such as c#/java that it is unnecesary. My sample just shows what I meant (whether it is really Hungarian or it is half Hungarian) there is no need to indicate the type of the variable in its name. - pablito
(1) @pablito: Why do you think App Hungarian is suddenly less useful in C# than in C/C++? Just because Microsoft said so and abandoned it? ;-) - Yarik
(9) @Yarik: Many reasons 1) you can know the type of the var just from the tooltip, intellisence, etc 2)it doesn't prevent bugs of bad type assignments since the compilation in this case fails 3) if the type of the var changes you have to change the name? 4) less elegant(readable) but this is my opinion - pablito
(2) @pablito: (1) a total miss: the key purpose of App Hungarian is to make errors visible to you before you even think about moving your mouse... - Yarik
(1) @pablito: (2) visual detection of bugs that compiler cannot catch is exactly the main purpose of App Hungarian... - Yarik
(3) true; but it is a real plague in Sys Hungarian, not in App Hungarian; - Yarik
(1) @pablito: (4) true, neither of Hungarians is very elegant; but when elegance conflicts with robustness... well, at some point I've become a believer that "elegantly looking bugs" are too high a price for elegance per se. :-) - Yarik
@pablito: And, by the way, neither of the reasons you gave so far has nothing to do with "modern languages vs. older languages". They are equally wrong for any language. :-) - Yarik
(3) @pablito: If you did not read, please take a look. It explains the real Apps Hungarian (and its difference from Sys Hungarian) much better than I can using all these tiny comments. - Yarik
(1) Here is one of the real problems with App Hungarian: Invention of a good prefix requires certain amount of up-front thinking. And often it is too much (esp. when you are in a hurry). Ironically, that's exactly when even most faithful adepts of App Hungarian start slipping into Sys Hungarian. - Yarik
@yarik: the reason that in c# I see it ambiguos to prefix the type of the var is because in case you made a bad type assigment the IDE underlines you the error before compilation. Anyway you're are right about the complexity of the Hungarian thus I edited my answer removing the Hungarian. - pablito
(2) Anyways I still believe why (only tyoe prefix not Hungarian) should not be used in c#. Please see this: - pablito
(1) @Yarik: Still, Apps Hungarian is unnecessary in strongly/statically typed languages so all the criticisms apply here as well: - Konrad Rudolph
(2) I prefer this style. I don't have to do any hunting whatsoever in order to know what type the variable is. - SnOrfus
(1) Good point @SnOrfus. It may look silly in the declaration, but advantages are readily apparent in code longer than just a few lines. - kalyanji
(1) Hopefully, the name of your variable will tell somewhat what it is, and therefore what type it could be. If you're in Visual Studio or another smart IDE, doing a simple mouseover tells you. If your functions are getting so big you can't keep track of your variables, you may be deeper problems. - Stuart Branham
(2) The two types of Hungarian notation are (1) what Simonyi actually wrote about, and (2) what Microsoft actually used in public-facing code. I consider (1) to be potentially very useful, and (2) to be mostly useless. - David Thornley
(8) I'm against Hungarian 100% -- buth apps and system. In the Wikipedia example, what is wrong with rowPosition? why use rPosition? Why be ambiguous? Certainly, if the project I was given had a document outlining what each notiation meant I would be less against it. Good luck with finding that doc. - Nazadus
It seems everybody on my current project is doing that and reading the code hurts. Somebody even went in and changed some code I'd written in the past and added all those stupid and useless prefixes. - Thomas Müller
(3) Microsoft! Win32 is a prime example of (perfectly valid) but awful naming conventions. tagHEYGUYSIMASTRUCT *LPHEYGUYSIMASTRUCT - Nick Bedford
(4) After reading Joel's article, I still think Hungarian is Satan spawn. What makes Hungarian evil is that presumes that other developers have not changed the underlying meaning of your value. So you see a value called "sFoo" thinking it is Safe but someone has later removed the code that would have made it safe. Even if you decided to that HGN is a good thing, there is no reason for being so terse. Make your intent clear even to a developer that doesn't have the magic decode prefix ring. - Thomas
(1) Whether it's Hungarian or not, I can't stand to see this and that goes for an underscore in front of the name also. Use meaningful names and keep your methods short. - kirk.burleson
Granted, prefixing variable names is not necessary, but it is useful. It saves time, especially when working with variables of different base data types (e.g. when doing math with 16-bit and 32-bit variables). - Jim Fell
(3) Joel makes a good point on the value of App Hungarian; also, $htmlSchedule, $jsonSchedule, $arrSchedule are a heck of a lot better than $schedule, $schedule2, $schedule3 or $scheduleForPage, $scheduleForAjax, $scheduleInRawForm. - Lèse majesté
(1) @Lèse majesté: But that's no longer Hungarian, it's just sane variable naming. - Vinko Vrsalovic
I kind of wish PHP required this - jasondavis
[+209] [2008-10-26 09:07:49] Ken

Inconsistent indentation.

I can put up with tabs or spaces, all sorts of brace matching, and various depths of indentation - as long as it is used consistently across a project.

(3) use python and you'll learn to object to the rest of stupid things. - Cheery
That use to be an irritant but Eclipse's CTRL-SHIFT-F changed all that, coupled with a good "ignore white space" while committing I can always look at code without cringing about braces. - Newtopian
(34) In Visual Studio, CTRL-K, CTRL-D will automatically fix up formatting... - Mitch Wheat
Cntrl Shift F in eclipse. This is the worst comment ever. - Stefan Kendall
We're in the 21st century. If you are using an editor that allows you to generate inconsistent indentation, then you're stuck in the past. Find something that can place your cursor correctly and/or auto-format your code, and upgrade to it. - Timwi
In Visual Studio, Ctrl-E, Ctrl-D works as well. It seems easier to remember for me. - DMan
(10) In vim, the '==' command will clean up indentation as well. - Maha
(3) @Mitch I've seen some code that even CTRL-K, CTRL-D cannot fix. VS just poops. - Nate
Likewise, Eclipse's code formatting doesn't always work. In every case where I've had to use code formatting (minified JS code), it would only format about 2% of the code. Perhaps that's due to an incomplete JS parser, but it's still rather pathetic. - Lèse majesté
An interesting approach from Steffen Mueller (… ) - using Text::FindIndent to adjust your Vim settings to the code you're editing. - Ken
haha In my university they take points out for inconsistent indentation. - Joze
[+204] [2008-10-26 15:43:27] David Grant

Inconsistent brace usage within the same construct:

if (something)

(48) Yes, I find the opposite ugly, braces around a single statement ALWAYS uglifies my code. Braces are meant only to group. This code is perfectly readable. - Atømix
(12) +1. I seen people make mistakes in C/C++ by adding a new method call, indenting and forggetting to add the braces. (with brace/no-brace other way round) - Mitch Wheat
(2) I do this... braces around a single statement don't look write either - Click Upvote
(1) That's not inconsistent! the rule is don't use braces for single function calls. I write code like that :-) I ought to mark you -1 for that ;-) - Blank Xavier
(5) There is no rule that you don't use braces for single statements, but virtually every "good style" guide will tell you that consistency wins. It's the same with comments - basically redundant, but in their redundancy allow other people to figure out if your code works as you intended... - DevSolar
(23) +1 As a fan of no-braces-around-one-liners, I use braces around all blocks if any blocks need them. - Chris Lutz
(2) Of course, you can always use extra braces to be sure: if (cond) {{ stmt; stmt; }} else {{ stmt; }}. - Loadmaster
I don't see anything wrong with that code. If you don't like to put braces around single lines then this is how it should be written. I would use braces simply because I always use them, not to make it look like the else statement. - kirk.burleson
(6) @Gary, Braces do much more than than group- they are the only way in C/++/#/Java/Script to declare a new level of scoping, which is not just "a bunch of statements". - David Souther
If's like that aren't that bad, consider that pattern using for loops its a lot more nasty - mikek3332002
(2) @Dave Souther, I agree. I'm not sure why someone that programs in a language where braces are so ingrained would think that a set of braces would make code ugly. This is especially true, in my opinion, when the set of braces could easily save you a potential future bug. A single statement, as Dave said, is still a new scope. Braces make it easier to get that when skimming code. - Chimmy
[+191] [2008-10-26 11:43:09] Yarik

Placement of commas like this:

enum Whatever 
    , AnotherValue
    , YetAnotherValue

I understand the rationale, but my eyes bleed when I have to read something like that. Very inhumane.

What I don't understand is why language syntax designers do not allow to have redundant delimiter characters at the ends of character-delimited lists. Of course, something like this

enum Whatever 

would be a little inhumane too but, in my humble opinion, not nearly as ugly as the first sample...

(2) I agree. I am so glad that trailing comma on the last element is allowed in Lua tables and C# enums. - steffenj
Agreed here as well. Just doesn't look right, even though I understand the reason.. - neonski
(12) C99 enums allow the trailing comma; C89 does not (so don't use them unless you're sure you're using C99, always). - Jonathan Leffler
(16) PHP, Ruby, Python all allow trailing commas. Several other languages as well. I commonly leave it in to make adding another entry or removing one easier. - jcoby
(16) Many constructs in C# allow for this, such as enums and object initializers. - Wyatt
(3) Add Perl to the list of languages which allow a trailing comma. - Dave Sherohman
C# allows trailing commas? Whoo-hoo!! Yet another good reason to migrate to C#!! - Yarik
(16) I disagree. I MUCH prefer the comma-before-values. Maybe it's just me... but once I got used to it, it just looks and feels better to me. - Atømix
(1) @Atomiton: What about other people? Alas, it's not just you. I worked with quite a few people who seem to rank "editability" of code higher than readability... - Yarik
(2) @Yarik: But I think the first one is more readable. An Enum is a list of items. Therefore, it follows convention. List Items are preceded by a bullet... or in this case a comma. Admittedly, I don't do this for Enums... but I will for String.format("{0} : {1} - {2}", value1, value2, value3); - Atømix
(3) @Atomiton: Hmm, it's an interesting prospective: seeing a bulleted list there. But it is quite far-fetched and has a very serious flaw: where is the bullet for the first item? ;-) - Yarik
(3) @Atomiton: Come on, it's an uphill battle to defend readability of this approach. No matter how you look at it, it breaks all kinds of common typographical/syntactic conventions. That's what makes it hard to read - by definition. :-) - Yarik
What's funny is C older than C89 allowed it commas at the end of enums. - Joshua
(2) PHP allows a , after the last element. I've got into the habit of using it. Javascript does/doesn't sepending on the JS engine. A comma after the last element is invalid in IE, but fine in Firefox. Can't tell you hoew many cross browser issues that's caused me. - Jim OHalloran
(3) If you put the comma before the value, you just reverse the problem -- superfluous leading commata. - Svante
(1) my boss gets on my case when I use trailing comma's in SQL statements for declare or select. Her argument being that with trailing you cannot just comment out the last line in a statement because of the previous trailing comma, where if its prefixed you can without deleting anything. shrug - SomeMiscGuy
(2) @Christopher: Some people believe that "editability" of code is more important than readability. Some even think that "editability" of one line during occasional editing spurts is more important than readability of many lines through the code's lifetime. This kind of "logic" escapes me... - Yarik
is PL/SQL it`s looking normal and useful - drnk
(16) @Christopher, but then you can't just comment out the first entry. What's the difference? - jmucchiello
(1) This is done a lot in SQL. I have no idea why. It's horrible. - Loadmaster
(1) That's awful. I wish people would follow natural human language as an example as to grammars in code. - Nick Bedford
The primary reason for doing this is that you can comment out or delete the line with no remaining syntax errors, rather logical actually when you think about it. - Robert Massaioli
@Robert Massaioli, In my opinion, I find it VERY hard to believe that fixing a single obvious syntax error would be worth sacrificing readability. This is especially true considering that we process a comma with our language backgrounds in mind, where it's generally grouped with the clause before, not after. - Chimmy
@Chimmy I did not say it was a good idea (I certainly do not do it in my own code). I am saying that that might be a reason why people do in the first place that would be a logical reason. - Robert Massaioli
@Loadmaster, Chimmy, Robert, and others-who-object-against-the-inhumane-comma: I think the MAIN reason for those who use the comma to begin an argument, like me do, is that we want the commas to be "aligned-able"! If the programming language allow the trailing comma, I prefer the REVERSE way: allowing a leading comma! Then, please pay an imagination, we all got both of the readability and editability at the same time: "readability" as a bulleted list, and "editability" as freely add/remove/comment on an argument. - Nam Gi VU
(continued) The "weird" style is especially helpful when writing the if-statement conditions where the operator, i.e. and/or/not or &&/||/!, always belong to next operands and so forth, should be put at the beginning of the line containing its operand. - Nam Gi VU
(1) @Nam Gi Vu: Who cares if the commas are aligned? What's more important is that the member identifiers are aligned. - Loadmaster
@Loadmaster: OK my friend, just don't care then... I only have to say this: you are maybe so fond of your style that you don't care about others - the style (with the leading comma) I suggest is well-suited your taste, ie. the member alignment, plus the ability to edit/add/remove easily at line-level! - Nam Gi VU
I believe Perl was the first language to allow trailing commas. Certainly it predates PHP, Ruby and Python mentioned above. - Andy Lester
Lua and Objective-C both also allow trailing commas on the final item. Really wish T-SQL did. - Jeremy Fuller
Note that in Python, the comma is sometimes mandatory to differentiate between a single value and a tuple: (1) and (1,) - ereOn
[+154] [2008-10-26 09:09:36] Terminus

GNU style [1], of course.


(1) What's so frustrating about it, in your opinion? - Sherm Pendley
(13) return type is on top of the function declaration. It looks out of place. - artificialidiot
(1) "What's so frustrating about it, in your opinion?" -- the indentation, of course. The fact that the ending brace no longer lines up with the statement it conceptually belongs to. - Terminus
(10) Indentation and brace-style is rather awkward. - staticsan
(1) It is just hard to read. - Ed S.
I don't do the return type on top of the function declaration, but I rather like the brace style. Besides, no text editor that is usable for programming can't match brackets, so if something doesn't "line up" you can still find where the statement starts. - Chris Lutz
(4) The return type on top convention has a deep-rooted rationale: functions are much easyer to find with grep. If you want to find the function foobar, you type "$ grep -n foobar raboof.c" and get the function declaration. Frustrating, yes, but usefull for old coots using vim and command line. - terminus
(28) I believe Linus Torvalds said something to the effect that the first step in writing good C code was to print out copy of the GNU coding standards and burn them. I agree; the brace indentation truly combines the worst of all brace styles. - Michael E
(3) Sounds a little like Stallman and his followers just jerking themselves off, and creating egotistical standards. - Dominic Bou-Samra
You could say that about any standard. If you want to criticize a coding standard, point out its flaw. Don't resort to petty ad hominems. - Lèse majesté
(2) @Lèse majesté: However, it does look like somebody set out to create a style that was deliberately different from all others, perhaps in a spirit of compromise. The brace examples are a good idea: there are reasons for K&R, line-up-with-if, and line-up-with-enclosed-statements. They are, obviously, different reasons. They settled on a brace style that has nothing to be said for it, thereby annoying partisans of the other three styles equally with anybody who just wants a halfway reasonable brace style. - David Thornley
(3) Criticisms: Spaces between function names and parens, which confounds simple greps; Indentation of 2 spaces is too small; Mid-dentation of braces is confusing; Function return type on separate line confounds simple greps and looks confusing. - Loadmaster
@Terminus: IMHO there's nothing wrong with the GNU style. Now the Whitesmiths style... - terminus
[+151] [2008-10-26 10:42:17] MusiGenesis

Spaceless concatenation like this:

string s = "Bob"+" "+objWhatever.ToString()+obj2.ToString()+"isadork";

I guess it depends on the language. In PHP, space-less string concatenation is okay, but I wouldn't do it in Icon (different operator). - staticsan
(1) @staticsan: spaceless concatenation is permitted in C#; I just find it annoying and more difficult to read. - MusiGenesis
(35) I have abandoned string concatenation in favor of String.Format. String.Format("Bob {0} {1} is a dork", objWhatever, obj2) is much clearer. - IMil
(1) @MusiGenesis: I think the reason it's better in PHP is because the operator (.) is so small it makes it a lot more readable than + or & in other languages. For example "Bob ".objWhatever.obj2." is a dork" works just as well with or without the spaces in my opinion. - CodeMonkey1
(1) Here it is less readable because of the true type font, but with a fixed width font, the . operator is almost like a space in itself. - CodeMonkey1
(4) Thank God VS fixes the spaces when typing the semicolon. - GeReV
Multiple concatenations already makes code unreadable, but explicitly calling ToString() to make it even more unreadable makes me crazy... - Thomas Levesque
(2) @Thomas: sorry, I just love parentheses, so calling .ToString() gives me two of them for free. - MusiGenesis
I don't think I've ever seen code like that. - kirk.burleson
I think what he was pointing out was the addition of "Bob" + " " + not the use of no spaces in between the addition signs (or both perhaps) - Jimmy
[+121] [2008-10-26 08:25:29] JTA

Overkill abstraction of object oriented design.

(16) Like, for instance, this: - Aaron Maenpaa
I'm facing this right now and it's driving me crazy! - dwc
++ Not just frustrating, it's possibly the biggest performance killer, because each abstraction level assumes the ones below it are fast, and assumes the ones above it will respect how much work it does. - Mike Dunlavey
(10) This is a design problem, not a style problem though. - Permaquid
The use of overkill is weird. Such a negative term. How about liberal abstraction? I actually hate the opposite, OO without enough abstraction. - tomwrong
[+111] [2009-02-24 19:23:27] SnOrfus

Not naming UI elements. I'm dealing with a codebase now that has a tabcontrol, and the controls in each tab aren't UserControls so I think it's up to Button37 and TextBox25 by now.

(3) haha nice one! +1 - jasonco
(7) Using WinForms in VS 2005 and later, you can set GenerateMember to false on a Label (or whatever) that you don't need to reference in code. Then it doesn't have to have a name, and you won't see "Label25" in Intellisense. - Kyralessa
Or VB6 control arrays of about 100 text boxes all named "txtInput". Really now? - Heather
Swing code which use variable starting with j, as in jlabel3. - Tom Hawtin - tackline
[+110] [2008-10-26 10:01:03] steffenj

Since programmers have to write correct code without syntax errors, I am overly picky when it comes to obvious typographical errors in variable and function names. Especially not since rename-refactoring is just a click away.

A few examples:


The last one being the worst of all.

Ah, I see lot of them in the large code we have at work! Lack of plural too (listOfUnsetNode for example). The fact we are French writing in English doesn't help... :-P - PhiLho
A pair that I had fixed recently were: get_extversion_from_inetrnalversion(), get_inetrnalversion_from_extversion(). I'd shoot the code reviewer as well as the coder! - Jonathan Leffler
One of the third party products that my company relies on has a table called "mistrake" that stores errors from various data imports. Just remove the friggin R already. - Cory Dee
(13) A mistrake is a mystical gardening implement not unlike a moonshovel. - recursive
@recursive: hahahah, nice one! - Mitch Wheat
(3) Finding obvious spelling mistakes that have been in the code for ages, erks me. OK, it won't affect the code running, but it smacks of laxiness. Often, a dev will notice it and not change it because they have no way of being 100% certain it won't break somewhere. (stored procs are a good example). - Mitch Wheat
(16) for the last 2 years I've been trying to figure out what the original programmer who named this method was thinking... LoadSchmulaka() - SomeMiscGuy
(3) @Mitch Wheat: Yeah, it irks me, too. Such mistakes certainly do point to laxness (or even laziness) on the part of the developers. - Adam Jaskiewicz
(67) I propose that the winner is "Referer", of HTTP fame. Every time a user clicks a link in a web browser, this 7-character brainfart is transmitted across the world. - j_random_hacker
(1) Every time something like this comes up, I remember the $date_dude variable in the Perl scripts I inherited at my job. - Artem Russakovskii
It is far worse when it is the name of a database table. - jmucchiello
(31) Re: "Referer". Just think of the gigabytes of data saved EVERY DAY by omitting that one 'r'! - Barry Brown
(2) @Mitch: "laxiness"? - MusiGenesis
(1) In the codebase I currently work with Wrapable is a very common class. But sometimes it's referred to as Wrappable. Turns out there is a line in one of the common include files: typedef VNWrappable VNWrapable; // historical compatability Someone never heard of search & replace? And yeah they even managed to spell compatibility incorrectly when adding the spelling 'correction' fix. - danio
(8) @Mitch Wheat: That should be irks, not erks. Ironic, isn't it? - SLaks
The sad thing is that if you don't catch those soon enough, you will have API/ABI issues later when you fix it... - luiscubal
(2) Original Unix: creat(). - Loadmaster
(1) Well... does the player have a winning game or not?! - Kaz Dragon
(1) My own peeve in this area is deliberate mis-spellings like "DeAllocate". - Permaquid
(1) World of Warcraft used to have a UI API function called GetNumLaguages. Eventually they did get around to fixing it. - Cogwheel - Matthew Orlando
My problem is trying to type "destroy" and ending up typing "destory" :P - RCIX
[+110] [2009-07-30 09:10:58] Marc Mutz - mmutz

I haven't seen SESE (Single-Entry, Single-Exit) mentioned yet:

int somefunc( somearg arg, someotherarg otherarg ) {
    int ret = 0;
    if ( arg ) {
        if ( otherarg ) {
            // ok, we're good
            ret = ...;
        } else {
            ret = -1;
    } else {
        ret = -1;
    return ret;

Makes me puke. Guard clauses are so much better:

int somefunc( somearg arg, someotherarg otherarg ) {

    if ( !arg )
        return -1;

    if ( !otherarg )
        return -1;

    // ok, we're good
    return ...;

+1. What's the argument for SESE? I heard it was so compilers could inline more easily... but I'm not sure if that's really true when i think about it. - Inverse
@Inverse I really don't think there is any argument now, I believe this was a rule written back in the early days of C development since debuggers were no where near as robust trying to trace multiple exiting code statements would be very hard. - Chris Marisic
(14) ugh. a vendor did all their customization code like this. The funny thing is, it was in python. And the example given here isn't nearly deep enough. this pattern really causes nausea when there are 5 or 6 levels of nesting. - Peter Recore
(5) I'm in favor of SESE. int somefunc(somearg arg, someotherarg otherarg) { int result = -1; if(arg == true && otherarg == true) { result = 1; } return result; } - kirk.burleson
(2) I use the multiple return guard clauses too, and still get some heat for it. The arguments for a single return usually go 1) It is a better design because the closing of database connection, disposing of objects, etc. can be better coded in a single place. 2) With a single entry and exit, you can make a single log "entering" and a single log "exiting" to more easily track the flow. - aaaa bbbb
(6) If you've got exceptions in the language, you won't have a single exit guarantee. If you've got try…finally (or something equivalent) then you don't need single exit anyway as the compiler will synthesize all that on-function-exit crud for you. - Donal Fellows
(2) Don't You love arrow heads? I've seen one that forced me to scroll like 3 pages horizontally on my 21" monitor. It got some nice for`s, continue`s, while`s in it too. Brilliant time waster. - Arnis L.
I like multiple return, as long as the early returns are highlighted in some way. Syntax highlighting helps, but a comment is usually better. - John Cromartie
SESE saved my life. - tomwrong
[+91] [2009-02-09 21:57:47] staticsan

The coding style that bothers me the most is people who comment out code in revision-controlled code -- and then never delete it! One step even worse is revision-controlled code that has dozens of files that are no longer used or even linked to. Grr..

Ever try using ClearCase with multiple branches per source file? Sometimes this idiom is necessary! - Ed Griebel
(6) @Ed Griebel: glad I've never had to use ClearCase then - just somebody
[+90] [2009-02-10 02:47:26] Ates Goral

Declaring all variables at the start of a function, away from the scope in which they're used:

void ugly() {
    int x, y, i, j, count, length, count2;
    bool done, match, nomatch, p, q;
    double f, g;
    char *buff, *buff2;

    // ...

(1) FYI, that's a requirement in C. There's is a workaround by declaring variables in blocks, but arbitrarily creating statement blocks just to contain variabled look awkward. - Raymond Martineau
(30) It used to be required in C. Hasn't been for a long time. - Ferruccio
(15) A function with that many variables probably needs to be more than one function. - Trampas Kirk
(9) I like that style, but not quite like that. Hate > 1 variable declared per line. Up-front declaration is nice when a quick glance shows what you're working with, and gives you a list of data you may need to validate. Although... variables are too visible/persistent/unnecessarily initialized. - Triynko
(1) @Ferruccio It's required in C if you're stuck with some legacy build environments. I had to fight tooth and nail to break my co-workers of the habit when they wrote Java, though. - Chris R
(8) I got slammed in my first-ever code review for not doing this. - MusiGenesis
(2) Required in C, but not in C++ where the ability to defer/avoid object construction until/if it is needed is required/recommended for performance - lttlrck
(6) The flip side is burying variable declarations in the middle of long function bodies so they are hard to find. It's a readability trade-off. - Loadmaster
(1) This is almost mandatory when you happen to code in VBScript to ease the pain of implicit global variable scoping. - ssg
(1) @Chris R: Just for the record VS 2010 is one of those legacy build environments when you are writing vanilla C and not C++. Come on MS C99 is only 11 years old, I know you can do it! Just try a bit harder. - Ukko
(1) Delphi also requires all the variables to be declared up front. - Loren Pechtel
(1) Fun begins when those fellas unnecessarily are defined as instance variables. Joy to work when there's like 30 of them and 3k+ lines of code. - Arnis L.
In Javascript I declare variables at the beginning of the function, since the scope is the function even for variables declared in a nested block. - CodeInChaos
@CodeInChaos: Since it makes no difference from the compiler's perspective, why not cater for human readability? - Ates Goral
(2) @Loadmaster: The more intuitive place I would look for a variable is around where it is used. I don't understand how lumping all variables in one place makes them easier to find (you have Edit -> Find after all...). - Ates Goral
@Ates Gora Because I find it more readable to declare variables in the block they are scoped in. Declaring them in an inner block gives the impression that their lifetime is limit to the inner block. - CodeInChaos
@Ates Goral, because with my text editor of choice it takes two keystrokes to find the declaration; none of this Edit -> Find stuff. And if I am using something that has Edit -> Find buttons, then I can typically just mouse-over the variable and it'll tell me how it was declared. So there's no reason not to do it, as for a reason to do it: it's required in most languages I use, and when it's not required, it's nice to be able to write code once and use it in more than one place without needlessly moving variables around when I switch to a compiler that does require it. - mrduclaw
[+85] [2009-02-24 17:12:57] Chris McAtackney

I found this the other day in work when trawling through our source control. I think it's one of the most creative uses of the switch syntax I've ever seen;

bool flag;

// snip

    case true:
    	// Do something

    	// Do something else

(14) Heh, imagine a code review now, and someone says: the "false" case should be made explicit. Of course, there should be never a switch statement without default case, so we could use that for throwing an exception... - Svante
If you were going for code coverage, and you used the convention of throwing an exception for the default case that will never occur you might end up disappointed that you'll never reach 100% coverage. - SnOrfus
Intriguing, but why did they use a SWITCH on a BOOLEAN? That's what IF/ELSE is for! haha - Triynko
(21) Obviously, there was a bug in the compiler that affects if/else expressions! - Kevin Panko
(9) They must have been worried about hacked booleans being fed into their program... - RCIX
@Triynko - Switch statements are usually implemented as jumps in assembly, with each case being a memory location, so it doesn't actually have to compare the boolean (it's potentially faster than an if statement). Classic case of sacrificing style for over-optimization. - smoore
@smoore - Given that the equivalent code written with an if/then is about twice as fast, it's obvious that using a switch is not optimal. Here's why. First, if/then also uses a jump statement, and it's an even simpler one that jumps to a static location based on a single bit, using a single processor instruction after loading a boolean and jump location into registers. Compare this with a switch that has to load the boolean value, calculate a dynamic jump location by adding the bool's value as an offset, and possibly even force the value to 0 or 1 so the calculated jump location is valid. - Triynko
@Triynko: The compiler isn't required to compile switch statements in any particular way, as long as semantics are preserved. If there is a difference, it's likely to be that break means different things in an if block or a switch statement. - David Thornley
I think that just triggered a headache! - sjobe
(13) I think Duff's Device is a more creative use of switch. - dreamlax
@David: I know what a compiler does. But assuming it's a "good" compiler, then unless it recognized the switch was equivalent to an if/else (semantically), it would most likely compile it using jump-tables and at the very least have to calculate an offset using the value, which would never be as efficient as using a boolean jump to a static address. As for the break meaning different things... not really. A break statement (which isn't even used in an if statement), would not mean anything different. It would have the same function... to jump to a location (after exiting the scope). - Triynko
@Triynko: The compiler would likely notice that there were two cases, and compile it into the general form of an if. A break statement breaks out of a switch construct, but not an if construct, so particularly if there's another break in one of the two cases it may have to compile it less efficiently. - David Thornley
I like it! But it should have the false case... - kirk.burleson
C++ requires the braces if any variables are declared (and initialized) inside a 'case'. - Qwertie
someone probably did a benchmark test of 10000 loops through and "determined" that switch statements were faster. >:( - DGM
[+75] [2009-02-09 21:56:25] Ates Goral

Redundant parentheses:

if (((x) && (isValid())) || ((y < 1) && (y > 100))) {
// ...

(2) Yes! That, and (in Java), return (expression); or assert (x == 0); - PhiLho
(47) Let's not get too carried away here, since redundant parentheses can avoid confusion. The C precedence table, too often copied in newer languages, is overly confusing and somewhat illogical. - David Thornley
(46) I agree on the (x) and (isValid()), but the rest is perfect IMHO - it allows reading the code without checking the operator precedence table in your mind... - DevSolar
(3) I don't mind a few extra brackets (as long as people format their code appropriately). - Mark Simpson
(1) I actually printed the precedence table for C and Perl and posted it on my wall. Doing that really helped me. The comparisons are always the highest precedence, then the &&, and the lowest is the || operator. The expression above is equivalent to: if (x && isValid() || y < 1 && y > 100) { } - Kevin Panko
(17) I guess you're not a fan of Lisp ;) - Matt Fichman
A little extra whitespace around the logical operators (&&, ||) can solve that. Using and, or, and not (which are standard C++ reserved words) helps, too. - Loadmaster
Learning operator precendence is important if you want to avoid unneeded brackets. float a = 3 / 4 * 4 + 1; is ((3 / 4) * 4) + 1 Multiplicative first, then additive - Nick Bedford
(4) @matt I know you are joking, but one of the advantages of lisp is that you cannot have redundant parentheses: adding parens always change the meaning of the statement, and there is no situation where a paren or bracket is optional. This actually improves consistency, which actually does improve readability. - Justin Smith
@Kevin Panko: I deliberately avoided learning the C and C++ precedence tables. I think I'm safer that way. I'm certainly less likely to write code that's hard to read. - David Thornley
(7) @David: I think that's really the way to go if you're interested in helping your fellow developers. if(x && isValid() || y < 1 && y > 100) {} may be easier to read, but only if I'm 100% sure of the precedence table. Otherwise, if( ( x && isValid() ) || ( y < 1 && y > 100 ) ) {} looks almost as good and will prevent confusion for less enlightened developers. - Eric
If you work with multiple languages that have different ideas on precedence it's a very good idea to use the extra parenthesis rather than risk having the compiler come to the wrong conclusion. - Loren Pechtel
@DevSolar, I completely agree. I don't think expecting everyone to have the operator precedence table memorized is a good sign on readability. I don't have to have to run through a list in my head to process a statement like this. Add a few parens and it makes it MUCH easier. - Chimmy
I prefer using and, or, and not instead of &&, ||, and !. Adding an extra space around logical operators helps readability, too. - Loadmaster
As an aside, when using macro parameters as lone arguments to functions/other macros, the parenthesis are redundant here: #define foo(x,y) bar((x),(y)). Of course, they're not redundant when surrounded with operators of higher precedence than comma: #define add(x,y) ((x)+(y)) - Joey Adams
[+73] [2009-02-09 21:15:09] Maurice Flanagan

Hungarian notation in any form

(53) What about in code actually written by Hungarians in Hungarian? - MusiGenesis
(4) I suppose in that specific case it would be ok ;) - Maurice Flanagan
(3) Do Hungarian programmers prefer Hungarian notation? I'll bet not. - Loadmaster
(4) @Loadmaster Well I can only speak for myself. I used to use it in my early years... then, to put it this way, I became international ;-) - Péter Török
(18) Normally I hate hungarian notation, but I like it for naming UI controls: btnOK, txtFirstName, cbIPAddress ... - Qwertie
(14) pnWhat vIs advSo adjBad prAbout adjHungarian nNotation? - dan04
[+73] [2008-10-26 09:11:17] Ather

When the variable and method/function names are as unintuitive as they can be:

void function1(int i, int j) {
    for(index, index++, index < 5) 
       for(index1, index1++, index1 < 10)

Code is meant to be as self-explanatory as possible and the most control we as programmers have is on things we can name/define ourselves (comments is really the next level and should be done only if required).

(19) You demonstrate another pet peeve of mine: using the canonical loop variables i and j as function arguments, preventing their use in the loops! ;-p - Shog9
(13) Which language has for-loops organized like that? It seems to be 'for (initializer, reinitializer, condition)', which is not the canonical C and C-derived order. - Jonathan Leffler
The canonical i/j/k loop variables are a carry over from mathematics (comp-sci being taught largely by mathematics professors for a long time until relatively recently). - SnOrfus
[+61] [2009-02-10 03:23:49] Tyson

Any code block in a ten year-old source file preceded by:

// Temporary hack - buggy as hell. Will fix later.

(11) Hey, you found my comment! Now fix it! - Jk but that made me laugh +1 - Chance
(13) This is acceptable when you are coding under a deadline. Do you program for a living? Are you saying you have never done this? - Antony Carthy
(3) Oh, sure, I've done that. But then I fix it later. I don't abandon it and let it sit there for the next several years until it causes a problem that takes time to fix. - Tyson
This is acceptable if the next lines are more comments explaining what is actually wrong. What are the bugs? Is this still here after someone fixed the bugs? I delete these comments reflexively. - TokenMacGuy
(12) You missed the date 02/07/1995 and initials xxx - lttlrck
(1) Sometimes there just isn't time to go back and fix stuff... and there's the danger of breaking things. Also, if it works a year later, maybe it wasn't such a hack after all! - flexxy
Guilty as charged, the comment in an SVN check in THIS IS A TEMPORARY HACK, NOT A FIX is very similar - johnc
That's called duct tape programming! ;) - Arnis L.
Only a year old? Consider yourself lucky. I've found those kind of comments in code written in 1998. - George
I don't understand why marking a hack as such is bad. What is really bad is making a hack and leaving it up to the next programmer to guess what's going on and why. - Yarik
[+57] [2008-10-26 19:07:50] MikeJ

Mixing the bracket styles between K & R [1] and that other style...

if (condition){

Inconsistent mixing of initialization with declaration

int x,y,z=0;

  x = 1;
  y = 1;

"that other style" = Allman - Jake Petroules
I actually use the "full style" (braces on their own lines) for "important" control flow, and more compact styles for stuff of lesser importance ("if (x > 10) x = 10;"). - Qwertie
(3) Even mixing styles for different statements could be forgiven and maybe in rational in some places. Mixing them together in the same statement is painful - MikeJ
+1 I hate see C# style in Java as much as I hate see Java style in C# code - OscarRyz
[+50] [2008-10-26 10:42:24] Yarik

Undocumented (uncommented) hacks.

After almost two decades in the field, I can tolerate the lack of comments in general, and I can tolerate justifiable hacks. But uncommented hacks?!...

(14) I agree. "// HACK ALERT" should be second nature to any programmer. - MusiGenesis
int ix = ( grid[index] >> field->second ) & ~( ~0 << count ); // code encountered this very day, no comment in sight... - DevSolar
(7) I feel it neccesary to qualify this. Just saying that a bit of code is /* a bit hackish */ is worse than no comment at all. On the other hand, explaining that a bit of code is not expected to correctly handle all corner cases, explaining which corner cases, and what happens now when it encounters those cases (raises an exception? divides by zero?) is correct. - TokenMacGuy
(3) I sometimes write more than a full page of comment to explain the how's and why's of an egregious hack. - Qwertie
(3) @Qwertie: So depending on how long it takes you to type that comment you probably could have just made the correct fix instead of a hack. - Matt Phillips
(2) Haha ... Uh no. - Qwertie
(1) There is nothing wrong with /*a bit hackish*/ if it's an obvious hack. There are hacks which are just hackish/lazy/need-to-make-deadline partial implementations, and there are this-is-really-esoteric-and-confusing-but-it-saves-me-100-lines-of-code sort of hacks. The latter requires in-depth explanations. The former just requires a warning so that you know to come back and fix it later. - Lèse majesté
[+50] [2010-03-27 17:24:40] Gabriel Cuvillier
if (SUCCEEDED(hr))
    hr = ...
    if (SUCCEEDED(hr))
        hr = ...
        if (SUCCEEDED(hr))
            hr = ...
            if (SUCCEEDED(hr))
                hr = ...
                if (SUCCEEDED(hr))
                    hr = ...

                    // up to 19 nested if's...

Just because they heard one day that there should be only one return statement per function.

(2) I am at a loss of words to this. - Chris Marisic
(6) And of course, every function body is encapsulated with a big try.. catch(...) block, just in case. Aw... - Gabriel Cuvillier
(3) I unfortunately see this very often... - Ates Goral
Event chaining often leads people this way. Eeeewe - tomwrong
[+48] [2009-03-03 20:26:02] Ólafur Waage

Makes me want to cry, specially when you are deep in a nest of some sorts

(4) Could this just be a difference between your tab size settings? - finnw
No since the if statements were indented. - Ólafur Waage
(5) Emacs auto-indent FTW! - Brian Postow
(4) mixing spaces and tabs would get you this - Inverse
(1) Emacs is never FTW. Vim > Emacs. - ThiefMaster
[+48] [2009-03-03 22:30:24] Chris Lutz

In C, I saw someone get around the "two lines of code need a block" rule like this:

    doThis(), doThat();

While I understand wanting to shorten code, that's ridiculous.

(10) I don't understand wanting to shorten code. Are you trying to save disk space? - Trampas Kirk
(24) Sure you want to save disk space. It's so expensive these days. - Graeme Perrow
(7) +1 this is awe-inspiring - TokenMacGuy
(22) I'm going to start using this ASAP - lttlrck
(18) Wow, you can do that? AWESOME - Nick Bedford
(3) @trampas: lines and density of code mean more work to write, more chance for bugs, more work to refactor, and more work to read, and more work to debug. Terseness has a lot of value, but only when it doesn't sacrifice clarity. - Matt Briggs
I actually have to say if this was used solely with descriptive method names this is abundantly clear, now if you use any regular code this would be a nightmare. - Chris Marisic
(3) @Nick you can do that and do this. - kenny
(2) @Chris - I can't find the code that originally inspired this answer, but it was something like for(/*something*/) x += y == '[', x -= y == ']' - Chris Lutz
yeah that would be ridiculus - Chris Marisic
You gotta love C... - kirk.burleson
(2) I think this is used in jQuery to reduce the total footprint coz two characters ({ and }) are more than one (,) - Atanas Korchev
(1) @korchev: actually, it's 4 characters ({;;}) versus 2 (,;). And I also want to point out to Trampas Kirk that this is usually to save screen real-estate. This isn't a problem when you're working with short code blocks, but, with longer code blocks, fitting more code on screen allows you to get the full picture of what's going on without having to scroll up and down. I don't find this style at all unreadable. - Lèse majesté
(1) A fairly common idiom in very old C was argc--, argv++, used in command line argument parsing loops. - Loadmaster
@Loadmaster - I've done that, though perhaps with a semicolon instead of a comma. See my comment above for the approximate actual code that inspired this answer. - Chris Lutz
The comma as a statement separator is acceptable in for loops and macros, pretty much anywhere else I can't see a reason why it should be tolerated. - Nate C-K
[+38] [2008-10-26 11:59:00] Atanas Korchev

I just don't like prefixes in front of class field names: string m_name;

They are kind of useless, but at least they used to be the Microsoft-recommended way, so it's kind of understandable that it crops up from time to time. - MusiGenesis
(24) They are absolutely not useless. Quite on the contrary, they're very much required, considering that you'd else risk name conflicts with public properties. Differentiation on capitalization alone is quite error-prone and doesn't work in languages like VB: - Konrad Rudolph
(5) I would always go for using or - Atanas Korchev
(18) I also think this is essential. I hate looking at variables and trying to figure out where they came from. I always think I missed the declaration of a variable when reading the code and stumbling upon a member variable without an m_ preceding it. It wastes time trying to find where it was declared. - Dunk
(1) -1, since i completely agree with #2 and #4. - mafutrct
(4) In PHP where you have to say $this->member, they should never be used. - jmucchiello
(2) When you're deep in a function and suddenly see "name", it'd be nice to know whether you're dealing with a local, global, member, or class variable... with g_, m_, and c_ you'd know. ;-) - DevSolar
(6) @devsolar just don't use deep functions. - Vadim Ferderer
(2) i hate having m_, but _ works great (when i remember)! - RCIX
(1) They are not useless, have nothing to do with Microsoft, but they are unnecessary if best practice is followed by avoid long functions and globals. Only constants need prefixing or capitalization. - lttlrck
@RCIX +1 I agree. Handy when you need public/internal accessible class properties. So the public/internal part can be accessed and sterilized with the PascalCase name ex. 'VariableName' and the internal non-sterilized private class variable would be '_VariableName'. - Evan Plaice
@RCIX, @Evan: IIRC, the _ is reserved for implementation specific functions/veriables in C and C++ - rubenvb
@korchev: How is this.var any better than m_var? - Loadmaster
[+37] [2008-10-26 14:42:30] Jon B

Useless variable names

int temp1 = 10;
int temp2 = 5;
string a = "test";

Yes, I see too much of them in our code! tempArray, aList, theManager... Erk. - PhiLho
(14) I think only the local variables which have a very short life time should be declared with these names. - andHapp
I'm working with some code with vars String1->String17 right now.... - annakata
int dataByte0, dataByte1, ... dataByte31; // USE A FRIGGIN ARRAY! - Adam Jaskiewicz
as long as the method is well documented, I really dont see a problem :S - cwap
(5) @Meeh - if the variables were named properly, the method wouldn't need to be "well documented" as it would be self-documenting - Alconja
@Alconja how would you name a temporary variable more descriptively? - lttlrck
(3) Perhaps with the intended usage after the 'temp'? Such as 'tempRowPosition' or 'tempFooArray'. - Ron Warholic
@RonWarholic: That is really gratuitous. If you're going to do that, then just drop the temp. @Stuart: Most variables are "temporary", but if it's only being used in a short code block and is something trivial (like the position of the last period in a filename, when trying to determine the file extension), then I usually use i, j, k, etc. - Lèse majesté
@Lese majeste: I've found that most uses of temp seem to occur when there is a variable in a parent scope that has the name that would make the most sense. This happens often with immutable types. In these cases using the temp qualifier to show that this is an intermediate result is acceptable and illustrates the transient nature of the variable. - Ron Warholic
@Ron Warholic: That's a valid point. But often you could do something like currentRowPosition or oldRowPosition, etc. - Lèse majesté
[+33] [2009-03-03 20:16:28] Chris

I watched this video Improving Code Quality with Code Analysis [1] from the PDC, and I couldn't believe this example which was provided.

public FldBrwserDlgExForm(): SomeSystem.SomeWindows.SomeForms.SomeForm
    this.opnFilDlg = new opnfilDlg();
    this.foldrBrwsrDlg1 = new fldrBrwsrDlg1();
    this.rtb = new rtb();
    this.opnFilDlg.DfltExt = "rtf";
    this.desc = "Select the dir you want to use as default";
    this.fldrBrwsrDlg1.ShowNewFldrBtn = false;
    this.rtb.AcpectsTabs = true;

This always makes me angry. When developers rename variables because they believe it saves time and effort. It makes my brain hurt.

Here is what it's supposed to say, you tell me, which one is easier to read?

public FolderBrowserDialogExampleForm(): System.Windows.Forms.Form
    this.openFileDialog1 = new openFileDialog();
    this.folderBrowserDialog1 = new FolderBrowserDialog();
    this.richTextBox1 = new RichTextBox();
    this.openFileDialog1.DefaultExt = "rtf";
    this.folderBrowserDialog1.Description = "Select the directory you want to use as default";
    this.folderBrowserDialog1.ShowNewFolderButton = false;
    this.richTextBox1.AcceptsTabs = true;

p.s. In the video she says it's a real MSDN sample. Which blew me away! Looks like something a junior would write.


I would give you a +1, but one of my complaints is using this. before ALL class variables (-1) so you get nothing. - Bill K
@Bill K My thoughts exactly. +1 for meaningful variable names (you'll be reading the code at least 10x more times than you wrote it, so readable code is more important than quickly written code). -1 For extraneous this-usage. - Trampas Kirk
+1 Definitely my pet hate too - Paul Suart
-0 openFileDialog1 is not a meaningful name. The second version adds verbiage, not information. - just somebody
(8) I actually like extraneous "this" usage. I like it that I can glance at a variable and know what it's scope is. (So call me hungarian :-) - Andrew Shepherd
(6) If there's one thing you can remove from variable names, it's the "1" at the end. - Qwertie
I've stopped using the MSDN, because most of the VB.NET examples on there seem to be written by a VB6 coder (which was to lazy to learn the new language). - Bobby
Yea i would also remove this aswell as indent the latter of = so the assigned values become aligned, as well as the =. - RobertPitt
Too much use of this, you can clearly see that the variables are members. - Kevin
Yes, for some reason my firm has a "War On Vowels" as well. I don't know what it is. I've never been tempted to suggest Vanna White as an IT consultant before, but I think her services are needed here! - glowcoder
[+32] [2010-03-29 19:52:30] Claudio Redi

Ohhh, I hate when I find tons of commented old code just because some people didn't have the courage to delete it completely :-p

// Code that was used 100 years ago
// DoSomethingCoolV1();
// DoSomethingVeryCoolV1();
// DoSomethingExtremelyCoolV1();
// MagicV1();

// Code that was used 50 years ago
// DoSomethingCoolV2();
// DoSomethingVeryCoolV2();
// DoSomethingExtremelyCoolV2();
// MagicV2();

// Code that was used 5 years ago
// DoSomethingCoolV3();
// DoSomethingVeryCoolV3();
// DoSomethingExtremelyCoolV3();
// MagicV3();

// Deleted buggy code
// DoUglyBUg();


I hate dead old code commented. It make absolutely no sense. We all use source version control tools!!!

I hate code commented out like that. Use /* */, at least. - Emil
[+26] [2009-03-03 21:54:06] Trampas Kirk

Code with stupid, pointless comments comes to mind:

public void doer() {
    for (int i = 0; i < 10; i++) {
        if (a == true) {
        } // end if
    } // end for
} // end doer

Yes, even on methods where the // end <something> comes only a handful away from the start.

(1) I've seen ex VB programmers who love this kind of commenting style. Some folk take a while to relax in the company of {braces} - Richard Ev
(11) I only do that if I have several if / for / while statements nested and it's not easy to tell what scope a particular brace is closing. Then I leave myself a TODO: refactor this ugly routine. - Graeme Perrow
(1) I agree. If your methods/loops/conditions are so long/complicated/nested that you need "//end <blah>" then your code clearly needs to be refactored. Big code smell. - Alconja
Huh, I've always commented my ending braces, gasp. - Xepoch
+1. I'm working in a lousy code base now that has these all over the place. Every file I edit now, I first do a :%s/}..*/}/c in vi (making sure not do delete any } while (foo); lines). If you think you "need" these, then either 1) your functions are too long, 2) your indentation is poor, and/or 3) you haven't learned how to match braces yet in your editor (use % in vi). The worst is things like while (foo) { ... } // end for. - Dan
... and let me add, the developers of this code I'm working with now suffered from #1, #2, and #3. Lucky me. - Dan
(1) If there's a need to comment the end of the loop then your code is too complex. - Loren Pechtel
I agree with this, but sometimes you can't get the funding to refactor the code the way you want it to. If you can't get approval for a refactoring project, you damn well better take the 10 seconds to at least make the person who has to go into this code next have an easier time in it! - glowcoder
[+26] [2009-05-06 14:23:09] jsight

Hiding the first line of code behind an opening brace:

if (isAdminUser())
{ launchNukes();

I've seen code where this was done 100% of the time. Its always hard to read.

This seems to be contagious as well. - Permaquid
[+25] [2008-10-26 14:43:33] Mitch Haile

I hate it when there is no style--every engineer just does whatever he wants and the reader can tell which parts of a file were written by which engineers.

(1) I find its worthwile, especially gives a good idea who really wrote the code when it was copied and pasted or written over the shoulder. - Joshua
(6) That's what source control is for. Programmer personality is not something that should be reflected in the code, changing from one line to the next; the code should be a cohesive body of work. The style, the handling of errors, etc should be standard for the project. (Scope of "project" may vary.) - Mitch Haile
Even if there is a common formatting style (which there should be), I find it's still easy to tell who wrote something because each developer has their own favorite patterns, constructs, etc. - Outlaw Programmer
Right, but I am talking about very cosmetic stuff. Joe's whitespace vs Steve's whitespace. It also drives me crazy when Joe is inconsistent in his own style from one line to the next. I never know what to make of that. Is Joe just banging on the keyboard, and when it compiles he checks in? - Mitch Haile
(2) We had a developer who had his own style, but would only remember to run the code beautifier on 50% of his stuff. This would result in half of his code following company standards and the other half following his own standards. I agree, it was very annoying! - Outlaw Programmer
(1) In theory, it's kind of odd that the beautifier wouldn't be part of a pre-commit hook to SCM or part of a build step, etc. But not everyone has time to implement all the stuff required in a perfect world. I sure don't. :-) - Mitch Haile
(2) +1. Having to handle four different ways of logging and five different styles of error reporting ain't fun. - DevSolar
(1) It's great for apportioning blame, useless for everything else! - Christian Hayter
So if you have 20 developers on your team then you need to tell each developer to use a different number of spaces for indenting? Because it's very likely that more than one developer will use the same indenting/bracing style. It makes much more sense to use code control (which you should already be using in the first place), as Mitch wrote, to assign blame. - Lèse majesté
Regardless of standards, after having been a contractor for awhile bouncing between projects I've kind of picked up how to not only determine who wrote the code but roughly how long they've been a programmer based on their style. Sometimes it's a bit disconcerting. - Chris Lively
[+24] [2009-07-15 16:14:45] ya23

Space between function name and brackets. "Reversed" spacing around keywords - I'd use if (true) instead of if( true ).

fun1 () {


fun3() {
    if( fun1 ().fun2 ().fun3() ) {

    while( true ) {

This really hurts my eyes.

(1) +1, it blurs the readability between functions, keywords, and conditions. And it drives me crazy that it's becoming so popular... - Inverse
(3) Hurts my eyes too. My rule is that functions "glue" to the open paren. if/while/for/switch/catch are not functions, so put a space between them and the open paren. Never put a space after a left paren/bracket or before a right paren/bracket. - Dan
[+23] [2009-04-03 15:50:51] Tarion

Leaving the brackets before a longer loop.

while(foo == bar)
    for(i = 0; i < count; i++) 
        /* code */

Or a bit more ugly

while(foo == bar)
    for(i = 0; i < count; i++) {
        /* code */

One more:

while(foo == bar) for(i = 0; i < count; i++) {
    /* code */

(23) While I consider the first 2 perfectly acceptable (depending on the language), the last one should merit death for the person who wrote it. - Dan Herbert
the 3rd one's just nasty lol - user176121
Once I read this post I didn't mind it so much:… - Andrew Shepherd
What about: for (i == 0; i < count && foo == bar; i++) { /* code */ }? I know the logic's different, I'm referring to the coding style. - Flynn1179
(1) I use all of those. Looks nice to me. - Arnis L.
Totally agree with @Dan, proper indentation prevents confusion. - golergka
[+23] [2008-10-26 14:39:34] PhiLho

The worst I saw was on some well known open source network code in C (I can't recall the software name): the author defines a bunch of pre-processor shortcuts (like W for while, and worse) and use it through the whole code...

I also saw an ex-Pascal programmer defining BEGIN and END to { and }...

Hey! This was my pet peeve!! - Ed Griebel
BEGIN and END are the worst dam thing .. just Why would anyone long to use them so???? - hasen j
(5) Fortunately, for preprocessor hacks like this, there's an easy tool to fix them - gcc -E. - Chris Lutz
(7) +1 for the BEGIN END thing, but taken a step further and actually enforcing it company wide in a "style guide"... - lttlrck
@hapalibashi: I seriously would either ignore that or leave. - 280Z28
Personally, upper-cased keywords in Pascal are frustrating to me. (And anything besides lower-cased; but upper-cased especially -- makes language look Basic-ish.) - Regent
[+23] [2009-12-18 19:24:46] tkyle

This is one that continually blows my mind when I see it. I've actually come across this more than once.

if (A) {
    //Do something
else if (!A) {
    //Do somehthing else

+1 I fear for the coders' job xD - The Guy Of Doom
lol that's hilarious - how did they get the job? - Dal
And code like this is why I love resharper to giving me warnings for code that is unreachable. - Chris Marisic
@Chris, I think the code is reachable; it's just stupid. - Hamish Grubijan
(1) Formally, A may do something that changes its own result. For instance, first (A) is false (sets its value to true and returns false), then the 2nd (A) is true, making (!A) false, and no statement is executed. (I don't endorse that kind of programming...) - ring0
But what if? I mean you have to prepare for the worst... - Ates Goral
(2) That's nothing. I've seen if(a < b) { //do something } else if(b > a) { //do something else } - jdizzle
@jdizzle: That has a totally different meaning, and can be totally fine depending on the context- - poke
@poke if by "totally fine" you mean "completely stupid"... - jdizzle
(4) @jdizzle: No, because there is a third case a == b which isn't looked at that way. And that might be the intention. - poke
(4) @poke you're not understanding the code. Look at it again. The else-if condition is the same condition, just with a different ordering of the terms. When would it ever be useful to write if (A) {} else if(A) { }??? - jdizzle
Oh lol, I didn't even notice that! Thanks ;) - poke
hahahahahaha this made me laugh. - Joze
[+23] [2009-11-04 05:18:18] Anders K

Once I worked with a guy who insisted on right-justifying declarations in C++:

class X
    int       asome;
   long  bsomeother;
 string     astring;


(1) That's not that bad.. - Brendan Long
after doing some Mac and iPhone programming I know what you mean. - Anders K
at least he left justified the data types - johnc
(7) Bleaauuurrrrgh! - Christian Hayter
[+22] [2010-01-31 17:21:55] Ondrej Slinták

Space between every single line makes my eyes bleed:

function doSomething( ... )



    printf( "whatever" );

    foreach ( ... )





(7) This usually happens when you copy&paste code from an Outlook email ;-) - vobject
(1) @vobject, if not by sending yourself emails, how else would you make sure that you do not lose valuable code? - Hamish Grubijan
[+22] [2010-03-28 02:26:34] Dan

Super long comment blocks for super short functions

// Method: getFooBarThing
// Description:
//    Get the Foo Bar thing
// Preconditions:
//    None.
// Postconditions:
//    None.
// Throws:
//    None.
int Baz::getFooBarThing()
  return fooBarThing;

No joke. Just a little exaggerated.

(8) Not really an exaggeration at all. I've worked in a company before where function headers had to be that long. - baultista
(1) Wow. I don't even write headers. I will start now, this seems like a nice template, thanks :) - Emil
[+19] [2009-03-03 23:00:39] John McCollum


$out = "
    <p>Yeah, you guessed it, whole pages of html inside a string, with <a href=\"mypage.php\">links</a>, variables like this: $txtOneContent -  and all without syntax highlighting because it's all in a damn string!</p>
    <p>Make one tiny and innocuous change, and the website explodes.</p>
echo $out;

(2) +1 for syntax alone :) - MPelletier
(1) I used to do this in my (really) early days of programming, ONLY because I had no idea of how to write it otherwise. I am wiser now, though. - Emil
[+18] [2009-03-07 00:02:45] Diego Jancic

I really hate when people assign the same variable twice, for example:

DataSet ds = new DataSet();
ds = GetSomethingFromDB();

The first line is totally useless! who writes that doesn't realize that it will be overwritten in the next statement, it's wasting memory.

(6) The real problem is not the wasted memory but the ignorance of the programer who writes it. (this code means that he doesn't understand how OOP works - Nicolas Dorier
Yes... you're right. - Diego Jancic
(8) Wastes MY memory :) - Benjol
It's valid when variables must be initialized to avoid compiler errors, because you do conditional assignment to the variable. - RCIX
(8) This isn't a matter of not understanding OOP, this is not understanding code in general. - Loren Pechtel
@RCIX this is never acceptable. Null is a perfectly fine option that does not waste resources. If for some reason GetSomethingFromDB is not called due to the flow of conditional logic then an empty ds should be instantiated elsewhere. - Kleinux
[+18] [2010-02-10 12:34:21] fastcodejava

Putting gaps between an instance and method :

object     .     somemethod ("");

(7) what ... why ... uh ... fail review - johnc
Agreed. It is a pity the language syntax accepts that... - ring0
Inconsistent syntax prevents you from searching for tokens with certain patterns (unless you have an IDE that can find declaration/definition/references for you). - Ates Goral
(3) going through this list, this is the only one I see that makes no sense and can't believe people actually do this.... - Jesse
[+18] [2010-06-25 18:13:01] Nick

I once worked with a guy who prefixed every variable, function, method, module - everything - with a 'z'. Why? To indicate his authorship; 'Z' was the first letter of his first name. Worse, he would use names like zString1 and zString2.

What a zTool that guy was. - Kevin Panko
Seriously. Drove me nuts. Sometimes if he'd already used, say, "zSomeValue" he'd create another one called "zzSomeValue". - Nick
So I guess they were boring names? zZzzzz... - Loadmaster
(5) you could get him to stop it by renaming all variables in all buggy code you found with z - johnc
(10) Maybe he was French, and it was just his way of saying theString1; theString2 - jdizzle
[+15] [2010-06-24 23:33:35] serhio

Indian variant

if (myBool.ToString().Length>4){// do something

(2) I don't know this. What is meant by "Indian variant"? Does that line mean if(!myBool)? - Phil
myBool.ToString().Length>4 means false in indian variant ??? - Luc M
(5) yup, looks like code from India. You hope they never hit a "pirate style" programming language where you obviously write "trrue" - flq
(2) Maybe they get paid by the number of source code characters they write. - Loadmaster
(7) I remember when I used to think all coders were passionate and talented and actually cared - johnc
(5) Imagine what happens if, in a certain language, Boolean.ToString() is affected by locale. - Ates Goral
[+15] [2009-05-30 23:09:12] Mark Simpson

I could spam a whole page on this one. Pet hates include:

  • Splitting declaration and assignment for no reason whatsoever. It really gets me confused when someone declares a variable and uses it 3 pages later. Apparently it's cool to declare all of your stuff in the same place regardless of where it's used... no. Stop that.

  • Packing code onto the screen like it's 1980 and we're all using 320x240 screens. This usually involves no spacing when using operators. People who do this usually miss the point. If you want to take in the whole problem on one screen, break it down into nicely named subroutines and it will read nicely and increase comprehension.

  • Crap or abbreviated naming (to the point where it reads like a text message).

  • Re-using variables for multiple purposes. I think everyone has seen this one somewhere.

  • Using comments where self-documenting / literal code would do the job. You just lost half of my screen space repeating yourself. Instead, call a function named after whatever the thing does, remove the comment.

  • Magic numbers. Named constants are your friend, as are enums.

  • Check multiple input conditions, resulting in the default nesting in a function being 2+ deep. Invert the ifs and return immediately, no nesting needed.

E.g. Potentially really messy:

if(someVal != null)
   if(someOtherVal != null)

       ... 10 years later

This is generally cleaner

if(someVal == null) 

if(someOtherVal == null)


(7) Or, why not, if (someVal == null || someOtherVal == null) return; - Lucas Jones
(1) Or just use switch - Kaji
There might be reasons for keeping the someVal and someOtherVal tests separate. One might be that you want to set a breakpoint on only one of them (not a strong argument, because you can always change the source temporarily while debugging). But most importantly if someVal and someOtherVal are two completely different things it might make more sense to have the code separately. - hlovdal
You last point is the same as I make in this question,…: Never test the normal case, test exceptions. - hlovdal
[+15] [2008-10-26 08:19:14] RWendi

I hate it when people declare/use undescriptive variable...


string zp = string.Empty;
int n1 = -1;
List<object> xList = new List<object>();

Rwendi, could you please not link to your website at the bottom of each of your messages? It is annoying and distracting to readers. Thanks. - Luk
especially when the site is really slow to respond - Steven A. Lowe
Also, there's a link to the webpage right in your user profile. If it's not relevant to the answer, don't put it there - people can find your webpage easily enough if they need to. - SpoonMeiser
ok, no worries... - RWendi
You'd not like haskell ;) - Henrik
(6) zp as in zip, n1 as in negative one, what is nondescriptive about that ok i kid i kid ;P - mike nvck
(1) @mike nvck: Code should be easy to read by anyone in the target domain. Why does "zp" represent the emptyness of a string? Why would you need to declare negative one if it couldn't change? Also, why is it describing the value itself, and not what it does? I recently had this problem in a school project. Groupmates used variables like "br" and "ct". "Br" was a Scanner object, and "ct" was a count of items in a file. Gah! - Stefan Kendall
@stefan: That's exactly how I read the code... But "xList" tripped me up.. There were too many ways to interpret it. ;) - Chris Lively
[+14] [2009-11-05 16:33:34] Langdon

Not necessarily a programming style, but more of a by product of being ignorant, or totally unaware of how to use the given IDE... I hate it when I open up a file and find crazy amounts of errant white space to the right of the line. Generally when I find this, I also find a mishmash of tabs and spaces. Example:

public string Test()
    code();                                       < 25 spaces or tabs here

It's annoying that none of the dozen or so IDEs I've used over the years strips extraneous trailing whitespace from source code lines. - Loadmaster
Visual Studio does if you run the code format function (CTRL+K, CTRL+D under C# settings). - Langdon
(2) @Loadmaster: VB6 (and probably earlier) did it. @Langdon: You can also do a regex find and replace, replacing " +$" with empty text. That's what I do. - P Daddy
Well, yes, eliminating/normalizing spaces and indentation is the first thing I do when importing foreign code into a project. It's only a few replace-regex calls in XEmacs. BTW, your regex should be "[\t ]+$". - Loadmaster
All my programming modes in Emacs do auto line-end trimming when the cursor visits it (made a minor mode for it). I end up committing a lot of files with description "Tidy up whitespace" to repositories. :) - vhallac
[+12] [2010-01-23 21:31:47] iBiryukov

My Java lecturer was obsessed with tabs, for which I hated him:

public void method() 
    for( int i = 0; i < 10; i++ )



[+12] [2009-04-16 15:06:44] Peter Perháč

The following drives me mad

If (evaluates_to_boolean) then return true else return false;

Or the highly contagious horizontal alignment:

MY_CONST_ONE    =  1;
MY_CONST_TWO    =  2;
MY_CONST_TEN    = 10;

I'm saying it's contagious because I feel bad for breaking it, so I will tend to keep it up. Let's say, were I to come along and add a MY_CONST_TEN_THOUSAND_AND_SEVEN, I would most probably spend time aligning the rest of the code...

MY_CONST_ONE                      =     1;
MY_CONST_TWO                      =     2;
MY_CONST_THREE                    =     3;
MY_CONST_FOUR                     =     4;
MY_CONST_TEN                      =    10;

It's a waste of time to make things align horizontally.

I'd recommend reading the book by Robert C. Martin's - Clean Code. An excellent book! Every programmer's must-read.

I know that's stupid but I can't resist to align horizontally. I can't. - Luc M
(6) It drives me mad if I encounter unaligned code. And I don't feel it's a waste of time to make things align horizontally. - René Nyffenegger
While I'm not so anal as to align the very end of every line like in the examples shown, I make an effort to keep the assignment operators aligned in order to ensure that things are easier to read. - Kaji
(1) I'd vote up for example 1, but aligning constants and variables, I like 'em neat and straight sometimes. - MPelletier
I personally like horizontal alignment, but calling it "contagious" is a fantastic description. I've never thought of it that way. - e.James
(2) Thank god column mode editing exist in my IDE!!! :) :)… - OscarRyz
Horizontal alignment is indeed quite contagious. Don't you all mean vertical alignment? - Wilhelm
[+11] [2009-05-30 23:11:46] Kyralessa

I saw this one in VB .NET and wanted to strangle somebody:

Select Case True

    Case SomeMethod()
        ' do some stuff

    Case SomeOtherMethod()
        ' do some other stuff

    Case YetAnotherMethod()
        ' do yet other stuff

End Select

I had to stare at it for a while before I understood the intent. And even then I was baffled at what would make anyone think it was preferable to

If SomeMethod() Then
    ' do some stuff

ElseIf SomeOtherMethod() Then
    ' do some other stuff

ElseIf YetAnotherMethod() Then
    ' do yet other stuff

End If

My guess is the programmer read somewhere once that the Select Case statement runs 3% faster than the If statement in VB .NET. That's usually how abominations of this sort arise.

EDIT: For the unconvinced, consider this:

Select Case True

    Case True
        Debug.Print("Case 1")

    Case False
        Debug.Print("Case 2")

    Case True
        Debug.Print("Case 3")

End Select

What will the output be?

The output will be "Case 1". To the novice this is far from obvious, and even to the experienced eye this is a bizarre way to write code. Select Case usually deals with exclusive cases, but it doesn't have to; it uses the first matching case and doesn't evaluate any others. So in our SomeMethod etc. example, if SomeMethod is True, the other two methods won't even be evaluated. Yes, if you're experienced, you'll know this, but that doesn't make it a good idea to write code in a non-obvious, non-idiomatic way.

(1) That’s actually a pretty well-established idiom and once you get used to it this can be very useful (for example to select on object identity; beats multiple ifs). - Konrad Rudolph
And they do completely different things ? Without a break the case statement could execute all 3 methods, while the if couldn't. - NimChimpsky
No, this is VB .NET. You don't need a break statement. In both cases the code executes until the first method that returns True. - Kyralessa
I find this not that bad. - ring0
[+11] [2008-10-26 08:24:21] Gamecat

The use of different human languages for identifier names gives me the creeps.

(2) Do you mean human languages (e.g. variables named "first", "segundo", and "dritten") or computer languages (e.g. variables named "ruby" and "perl" in a Python script)? ;-) - Ben Blank
(1) it's fun when you come across others' code and the names translate into @$!!@% and !$"£$ of course when you happen to know the language. If I left a Slovak identifier in my code for other Slovak/Czech/Polish/etc... developers to have fun one day... - Peter Perháč
(2) Yes I mean human languages. I have seen classes in which several methods where in English and others in Dutch. - Gamecat
(1) Co-worker works with such a code base. I find it really funny. :D - Arnis L.
Ditto here. I worked on a project that had French and English. So, I started naming variables in Spanish :D - tou
[+10] [2009-02-10 00:57:35] Ates Goral

Intermixing double and single quotes in JavaScript, in the same piece of code:

var options = {
    foo: "Some text",
    bar: 'Copy paste is fun',
    wtf: "(" + x + ')',
    baz: "It's cool"

Yes, it's a convenience when your string literals contain quotes, but I prefer uniformity of style in code. It's not that hard (or relatively more unreadable) to escape quotes using "\".

(3) It's easier to read that way though. - Ed S.
(2) The wtf-option made me cry. - Emil
[+10] [2009-04-04 17:23:32] Jens Luedicke

Not indenting function blocks.

Like this:

void DoLotsOfStuff() {
int x,y,z,is_available,thread_not_ready;
double latitude,
if (0 == is_available) { printf("data not available"); }

// more stuff....

A co-worker (a student working on his diploma thesis) wrote code like this. Several functions up to 100 or 200 lines long. I made this example up, but it comes close to his style.

(2) Wow that's disgusting. From a very quick glance it looks like a function prototype followed by a number of global variables, followed by a "what's that doing there". - dreamlax
[+10] [2009-05-30 22:40:02] Alex

Building in-line SQL code (horrible in itself), or even worse, SQL code that's prone to SQL injection:

sql = "SELECT * FROM users where UName ='" + username + "' AND pw ='" + password + "';

[+9] [2009-03-03 20:34:00] Bill K

I know a lot of people love this, but using "this." in front of every class variable drives me nuts.

The reason it's supposed to be used is to identify class variables. It's extremely bad at that since a missing "this." does not PROVE that it's a local variable.

Also, your GUI will color them differently. If you're not using a GUI that does, stop typing this. and go get a real editor! This kind of thing is why everyone keeps telling you to upgrade.

The real reason (and I can sympathize) is that programmers like consistency and it drives them nuts that you so often have to have this:

void func(String name) {;

to avoid collisions. Personally I don't have a problem with that inconsistency, but if I did, I'd use this solution instead:

void func(String pName) {

Relying on a manual process (like some programmer deciding to use "this." before every instance variable) is just going to lead to some time where you see a variable without "this." and ASSUME it's local. Use something more deterministic.

+1. Obsession with consistency is a smell that they have too much time on their hands. - finnw
I love the first :) But I only "this" if really necessary. - Tarion
Better to reserve p prefix for pointers - lttlrck
(1) All java class references are pointers--using p is not relevant to Java and would piss me off as much as "this.". Also, just because I didn't make it obvious, I prefer "this." to "p" when differentiating, but just don't like it used when unnecessary. - Bill K
(9) I thought people typed "this" all the time because it turns on their editor's auto-complete feature so they don't have to remember the names of the 150 inconsistently-named member variables in their poorly designed class. - Dan
@Dan I think it already filters to the available members, methods and locals if you just hit ctrl-space (not totally sure), all adding this. would do is remove the locals. It's possible that just typing ctrl-space would also give a list of all classes, so in that case this. would be an improvement, but pales in comparison to just typing the first 3 letters of the variable and hitting ctrl-space... - Bill K
(3) You've gotta say $this for each class variable in PHP. I find it increases code readability by making it obvious which variables are in which scope. Not to mention the syntax highlighting. - Lotus Notes
@Byron If it is required and consistent then it's possibly a good idea. Being optional in Java means that you can't trust it as a readability aid and it's simply junk. - Bill K
I disagree. Having a prefix that indicates scope makes all similar variable show up where you'd expect them in the autocomplete, the second example stinks like hungarian notation. Of course, I'd only use the 'this' prefix in the constructor or in methods where the parameter is in conflict with the classes' private variable. - Evan Plaice
@Evan Place for parameters I'll use/enjoy/accept either--it doesn't matter much and in that case something HAS to be done. My real problem is with people who use this. throughout the code... It hurts my head to read that garbage. If you read what I posted again you'll see that I wasn't advocating either, just theorizing on why people might use .this everywhere. - Bill K
You would hate php.. - Brendan Long
I'll use the first form only in constructors. It seems pretty obvious there. - aaaa bbbb
[+9] [2009-02-09 21:25:32] tapi
if (var = val) 
else {
    if (var = someOtherVal)
        if (var = yetSomeOtherVal) 

Sure it works but I actually saw this once and got and puked a little. In my mouth.

(1) In what sense does this "work"? Maybe I'm missing something, but it looks like someaction() will always be called if val evaluates to true. - MatrixFrog
= != ==. Assignments (=) always return true so all of the if statements will return true. It really shouldn't work. - Evan Plaice
@MatrixFrog, @Evan: Either he made a mistake, or it's a language that has another assignment operator. For example, I know this isn't Pascal, but in it you would use = for comparison and := for assignment. - Nelson Rothermel
(1) I thought assignment returned the right operand: ie, if (var = true){ doSomething(); } will call doSomething(), buf if (var = false) will not.... - Jeff Barger
[+9] [2010-03-27 17:59:11] Imbue

In C, I like omitting braces in single statements following ifs, whiles, fors, etc.

if (condition)

But some people take it too far.

i = 0;

if (i)
    if (i > 5)

In that code, SomethingElse() is never called.

(1) Using this all the time. For me it looks ugly only with bad indentation. - Arnis L.
Agree with Arnis. Never had a problem with that, unless the code structure/indentation is awful in the first place. - ring0
[+9] [2010-03-27 18:24:25] Permaquid

Comments that come after the code they refer to. And boilerplate in comments that adds nothing to meaning. Example (not made up)

int count_;
// effects: The number of objects.

I would be interested to know if (a) other people have seen this style (b) anyone prefers it to the alternative. I think this originates in the C++ standard. In Working Draft, Standard for Progamming Language C++ from 2005-10-19, section 17.3, which lists the conventions used to describe the C++ library. It provides a list of attributes for functions. It includes Requires, Effects, Postconditions, Returns, Throws and Complexity. In the context of a library it makes sense to list a function prototype and then its characteristics. It makes no sense to me to do that in the code itself.

There is a style, unnamed as far as I know, in which all functions return a status code, and all calls to such APIs are placed inside an if-statement. An example is socket API calls in UNIX. For example, if all api calls return -1 on failure you may see something like this for a sequence of API calls:

if(api1() != -1) {
  if(api2() != -1) {
    if(api3() != -1) {
      // all three api calls were ok - do stuff...
    } else {
      // handle api3 error
  } else {
    // handle api2 error
} else {
  // handle api1 error

It seems like many people are completely comfortable with this. But I do not like the way it pushes the error handling out of the picture, moving it away from the API call it refers to. When you combine this style with selectvely ignoring some of the errors and omitting the brackets on one or more of the conditions, or where some additional work has to be done before one or more of the API calls, you have a style where a maintainer has to check for correctness every time they deal with it. Though more verbose I prefer

if(api1() == -1) {
  // error - escape somewhere, maybe return -1 to caller.

if(api2() == -1) {
  // error - escape

if(api3() == -1) {
  // error - escape

// All three calls succeeded - do stuff here.

To me the latter seems so transparent that I have no idea why anyone uses the former. Except maybe it makes the programming seem more exciting, as you arrive breathlessly inside all those conditional brackets ready to do the real work.

(2) +1, I hate seeing comments after the code they refer too. - dreamlax
[+9] [2010-02-10 13:19:08] lorenzog

Amongst the many "programming styles" I've witnessed, the one I hate the most is:

the style that emerges spontaneously from the source code itself when many people 'fix' a bug and don't explain what they did

This can be shown with an example, coming directly from the code I'm debugging now (the person who originally wrote this left a while ago, and those who had to fix it can't remember what they did):

if ((a[i].Y - (((a[i].Y/b))*b)) < 75
    skipDiff += diff;

If you look at it closely, it contains everything one might hate in the shortest amount of lines of code:

  • uncommented hacks (the whole algebraic expression is a - a/b * b < 75 which is absurd, unless you realize that they are integers, thus the division is used to "round" something)
  • uncommented values (75 WHAT?!? )
  • over-use of parenthesis leading one to question his own mental health
  • counter is the outer for loop counter; yes, we are incrementing it inside the for loop as well as in the for loop condition. Oh, did I mention that it is used as an array index as well?
  • not only meaningless but also wrong variable names (I put 'a' and 'b' to avoid the customer spotting the code here, but the original variable names were something like _pageHeight -- which was not the page height, but the position you were currently at in the current page)

Also add that this code, albeit being on a version control system, has 2 revisions: the original checkin and the 'massive' revision that happened after a handful of people 'fixed' the code, which was on a single PC. And no revision comment was added.

while it's an amusing story of programmer idiocies, it's not a style issue at all. - hasen j
[+9] [2010-08-09 14:21:45] aib

Claustrophobic code:

int x;
    if(x==5) continue;
int y=0;//comment
if(x==1) something();
if(y==1) something();

I need my breathing space! Furthermore, whitespace can be used to group related statements (vertical) or tokens (horizontal) together.

[+8] [2010-03-28 02:29:02] Dan

Not understanding Boolean logic.

// If the foo happens or if the foo doesn't happen but the bar happens instead
if (foo || (!foo && bar))

Equivalent to:

if (foo || bar)

Even worse when there are more than two terms!

People actually do this!? - Daenyth
At least one person did. - Dan
[+8] [2008-10-26 10:02:51] JamShady

For me it's code that's deliberately hard to read, whilst ironically the developer thought they were making it easier to read. I posted this code snippet as an answer to another question, but it's just as relevant here. Here's an exact copy of code from something I work on, all the comments (or lack thereof) as identical to how it appears in the source code:

function getAttributes(&$a_oNode)
    $l_aAttributes = $a_oNode->attributes();
    if ($l_aAttributes === NULL)
        return array();

    $l_iCount = count($l_aAttributes);
    $l_i = 0;

    for ($l_i = 0; $l_i < $l_iCount; $l_i++)
        $l_aReturn[$l_aAttributes[$l_i]->name()] = $l_aAttributes[$l_i]->value();

    return $l_aReturn;

function getText(&$a_oNode)
    $l_aChildren = $a_oNode->child_nodes();
    if ($l_aChildren === NULL)
        return NULL;

    $l_szReturn = "";

    $l_iCount = count($l_aChildren);
    for ($l_i = 0; $l_i < $l_iCount; $l_i++)
        if ($l_aChildren[$l_i]->node_type() == XML_TEXT_NODE)
            $l_szReturn .= $l_aChildren[$l_i]->node_value();

    if (strlen($l_szReturn) > 0)
        return $l_szReturn;

    return NULL;

Someone obviously didn't read Joel Spolsky's article on Hungarian notation [1]. This code just makes my head hurt.


i hope this is Perl. or PHP. If it's neither on of these, you should find another job before you go mad! - Steven A. Lowe
Why would you hope this is Perl? Gibberish in Perl is no more acceptable than in any other language. - Sherm Pendley
Sorry, "function" is not a valid Perl keyword, it uses "sub" instead. And doing the whole C-style "for" instead of "for $l_i (0..$l_iCount)" would bug me if I saw it in Perl code anyhow. - Dave Sherohman
I think this is really well written code, honestly, considering it seems to be dynamically typed, it's made to avoid variable name conflicts. - Henrik
I think this is PHP - Click Upvote
It's PHP, and I can't see how it's really well written at all. The use of variable names is not at all intuitive, and in fact makes the code far more confusing to read than it should have been. - JamShady
(6) Say goodbye to that code, youy just released it under creative commons! - RCIX
I'm guessing l_ is local and a_ is argument? The next letter gives you the type: i is int, o is object, a is array (array of what?), sz is string (where did that come from anyway? It's used in many places). Hungarian isn't so bad in languages that aren't strongly typed, like PHP. I'm not convinced on the l_ and a_, though. Taking those out would make your eyes hurt less. - Nelson Rothermel
[+8] [2009-03-03 22:18:07] David Thornley

Code where the original developer used the names of his old girl friends as variable or function names (or, alternately, German numbers). That's the worst I've seen.

[+8] [2009-05-19 15:36:39] Gus Paul
MyObject o = new MyObject();
Debug.Assert(o != null);

MyOtherObject o2 = new MyOtherObject();
Debug.Assert(o2 != null);

Come on! I know John Robbins et. al. say use Debug.Assert, but you don't trust the runtime to create your object?

(3) Depending on the language 'new' might even throw an exception which means one would never get to the assert statement. - foraidt
(3) .NET languages either produce the object, or throw. The assert can never fail. - Qwertie
[+8] [2009-05-30 22:30:46] JustJeff
private static final int TWO = 2;

'private' no less ..

Me, I lost my temper by the time it got to int. - tchrist
[+8] [2009-04-04 16:43:16] happy_emi

Tabbing identifiers

a_namespace::a_class  a
int                   b
char                  c

There is no reason to write code like that... I wonder what happens if you have already defined b and c and then you need a. Do you spend time tabbing all the other variables? Brr...

(3) yes, I do. I don't do this kind of things always...but in some places it is really useful. It is far more easy to read the code. - Javier De Pedro
(3) I particularly like aligning ='s or :'s in lists of assignments. Makes things just a bit nicer on my eyes. - TokenMacGuy
Aligning makes it easier to pick out the names given more than, oh, four variable declarations. Especially class member variables. - Loadmaster
I very much prefer to have my variable names aligned like this, as I find it much easier to scan with my eyes. However, I always take issue with using interior tabs. Tabs should always be used for indenting, and never for aligning. You never know what the next programmer's tab width is going to be. - P Daddy
I woulda if a coulda. StyleCop yells "No!!!!!!!!" - Hamish Grubijan
I personally do, And have let me read very nice code - cMinor
I sometimes do that, but usually with some cutoff for excessively long or short types. In this case, b and c would be aligned, but a can screw itself - Alex Brault
[+7] [2009-03-03 20:39:56] tj111

Putting brackets on the same line as the code to execute inside those brackets. Here's some actual code from a web app I inherited. I will forever hate the guy who wrote this, as well as understand how PHP can get such a bad name (when used improperly).

if($Submit == "Complete Install" || $Submit == "Save Report")
    $dbStatus = "Open";
    if($Submit == "Complete Install")
    	if(trim($Desc) == "")
    		$Error = "Invalid 'Install Description' provided!";
    		$dbStatus = "Closed";

    if(trim($ContactID) == "")
    	$Error = "Invalid 'Site Contact' provided!";

    if(trim($ContactID) == "AddNew" && trim($ContactName) == "")
    	$Error = "Invalid 'Contact Name' provided!";

    if(trim($ContactID) == "Attach" && trim($AttachID) == "")
    	$Error = "Invalid 'Site Contact' provided!";

    if(trim($ProductID) == "")
    	$Error = "Invalid 'Product Serial' provided!";

    if($Error == "")

                //snip 150 lines


Also, note how register_globals is enabled (-_-). And this exact same logic is copied and pasted in at least 20 different files.

[+7] [2010-06-17 22:57:00] DeadMG

I've seen

#define ONE 1
#define TWO 2
#define THREE 3


(1) This is essentially what FORTRAN 66 did as part of the compiler. Everything in any call string was always passed by reference. They got smarter in 77. - Dave
[+7] [2009-11-03 20:06:31] void

Coding that uses a mixture of GNU and K&R i.e.

int function() {
    if (condition) {
        if (another condition) {
        else {

Unfortunately the code I maintain with has this bracketing style.

What the hell...? - Bobby
[+7] [2010-07-08 21:33:50] Corey Ogburn

She'd finish a line of code, she'd hit enter, hold space, and when the cursor gets "close enough" she'd start writing the next line of code there...

public func()
        int x = 0;
       double y = 0;
       string str = "";
              y = 8;
        x = 14;

I worked with her on projects in school going through pages of her code. First things first, I'd have to make it readable... then I began adding my code to hers. It made it easy to track her changes though.

Yeah I've got a coworker who codes like this. Fucking hopeless. - sashang
I don't understand. What is this for? Why would anybody ever do this? - Phil
(1) Most good IDEs have a button for formatting the file/ this nightmare can be undone within one keystroke...luckily. @Po: The same reason people are using spaces for indentation in text processors, because 'I've always done it that way and it works'. - Bobby
[+7] [2010-06-25 13:43:04] hoang

I "like" this one :

if (foo == bar)
if (foo != bar)

But my favorite is :

bool b = bool.Parse("true");

your "favorite" could be the only solution when parsing text files... - serhio
You use literal constants like Parse("true") for parsing text files? - Loadmaster
@serhio : this is not bool.Parse(yourInputStringContainingTrueOrFalse); I have really seen bool.Parse("true"); !textually! for initializing a boolean to true! - hoang
@hoang: perhaps that was a forgotten test in the code. - serhio
@serhio : not when it's done consistently thoughout the code ... anyway ... I got frustrated the first time and that's even more frustrating trying to find excuses ! - hoang
@hoang: If its done consistently, there is at least strange... :) Who wrote the code? I guess some Indians? see my 'frustration'… a propos - serhio
@serhio:A romanian woman, but we can't generalize ! - hoang
@hoang: Hm romanian programmers are not so bad. As for women, we can generalize :) - serhio
[+7] [2010-06-25 13:28:46] serhio

Space between ( and the rest )

(2) I use this style and it is more readable than without spaces, though. - silent
@silent: “more readable?” that’s highly subjective. FWIW, I really hate it but a friend of mine uses it throughout and I often work on his code. Gaah! - Konrad Rudolph
@silent: a "natural" English orthography seems me more "readable". - serhio
sorry, I don't know english as well as I wish :) - silent
@silent: there is no need to know English well to remark the relation between parentheses and text (that is, like this, without spaces). - serhio
(2) The flip side, which is every bit as awful, is to jam the controlling keyword up against the following parenthesis, as in if(expr). Combine the two and you get the truly horrid if( expr ). - Loadmaster
fortunately, Visual Studio >= 2008 fix automatically such a creativity, resetting the syntax to the "natural language" - serhio
FWIW "Code Complete 2" by Steve McConnell recommends this style - Matt Frear
(1) the "English" standard is using (this is some comments, without spaces) - serhio
[+7] [2010-07-08 21:14:00] user387091

Usually something like this:

               if (true)
                 if (thing = 7)
                   if (foo != 8)
                     Console.WriteLine("Don't delete me. I know what you did.");
                   while(foo == 8)
          switch otherThing:
             case "A":
             Console.WriteLine("Your answer is not B!");
             Console.WriteLine(@"Your answer is not A!
             You fail at life. Everyone hates you.");

Stuff like this: Constant switches, loops, ifs and do-whiles, without a SINGLE LINE OF COMMENT. It just makes me want to scream at other coders.

[+6] [2010-06-30 15:07:08] Brian Postow

I'm surprised that no one has mentioned this one. It's not as bad as brace misplacement, but I hate it when people put the one-line then branch on the same line as the if:

if(condition) dostuff;

It makes it MUCH more complicated to add debug statements, or set break points, and I never actually end up reading it correctly for some reason...

Screen real estate is NOT that expensive.

[+6] [2010-08-10 21:06:34] bedwyr

I've seen conditions written like these two snippets:

if(foo< bar) {
if(foo<= baz && baz!= 1) {

The developer wouldn't insert a space between left-hand variables and their comparators, saying he wasn't as interested in how the comparison was being done as much as which variables were being compared. This helped him better set apart the variables in the condition.

This was a very minor thing, but it utterly drove me up the wall every time I encountered it.

[+6] [2009-11-07 00:05:00] mmd

Multiple statements on the same line, e.g.

if ( condition ) { doThis(); doThat(); }

This takes readability down a couple of notches.

(1) totally agree, drives me bat shit - Jack Marchetti
Probably comes from the age when disk space was pricey. - fastcodejava
or worse, putting extra spaces in conditional statements and for statements - Inverse
+ spaces between parentheses and the condition :) - serhio
I disagree. English equivalent: "If you're at the store, please buy eggs and butter." The key consideration is the size and complexity of the statements. This should be broken up: "If you're at the store, please buy a 100 HP Dansing Extra-Octang Grinneling Hapling Frumhaugen and a Fofly Buvvelory Shalongibummy of 16 Grabring Jelogingings." - Ray Burns
[+6] [2009-02-24 16:48:57] Galilyou

A very strange C line of code:

int x = 0;
    int y = x+++++x;    /* what the hek !*/
    printf("y = %d", y);

Actually, this line doesn't pass the compiler check in VS and devc++ 4.9, but I believe it passed in devc++ 4.

y = 1... (and x = 2 after line 2), simple ;) - Henrik
(1) It's not how simple it is. It's how weired it looks like :) - Galilyou
(3) A nice case of undefined behaviour. - Alexandre C.
:) you should be able also to see something like x+++++++++++++++++x x---------------------x - serhio
is it meant to be y= ((x++)++) +x ? Eurgh or y = (x++) + (++x)? - johnc
@johnc undefined behaviour! ;) - Galilyou
[+6] [2008-10-26 09:50:40] codemeit

While Style is number 1, and functionality is number 2.

(9) Form over function. I know of a company in Cupertino that suffers from that. - lttlrck
[+6] [2009-02-09 21:00:44] PTBNL

I'd probably been coding for 20 years and working in Perl for a couple years before I saw something like this in someone else's code:

$y = 2 if $x == 5;

I'd never seen this way of writing an if in any other languages, and it took a while before my brain stopped automatically assuming that everything after the assignment was a comment. I don't know of any other languages where this would be allowed. I found it weird.

Ruby has it too, and it is quite easy to read once you get used it it. - Rontologist
If someone has to get used to reading code in a certain way to find it palatable then that is a problem. - Dunk
@dunk - Coming from another language, someone could say the same about <whateveryourpreferredlanguageis> as well. - SnOrfus
I love that in ruby. - Ed S.
(4) "Arse about face" would be my reaction to this code - Richard Ev
(3) it's in python 2.5+ and I love it. much prettier than a = b ? c : d - hasen j
Well, I think I'd say that a = b ? c : d comes in 2nd place for me ... Didn't realize that has been added to Python - I'm disappointed. - PTBNL
(3) This style is what makes Perl, Perl. Perl allows one to express code in many syntactical ways in more kind to spoken language. Some would say it is beautiful. - Xepoch
Although I agree it can be a horrible construct, I seem to remember the rationale for adding it to Python was along the lines of "if it isn't used by morons, it can make for more succinct code" SomeFunction(NormalArgument if Condition else AlternativeVariable) looks just fine to me. - porgarmingduod
I just wish the code highlighting would somehow make the "if" statement REALLY jump out so you don't mistake it for an unconditional. - Qwertie
What would this look like in Python? I know list comprehensions work like that, but variable assignments? - vlad003
HP Basic for OpenVMS has statement modifiers. - ninjalj
$test_condition ? $yes_var : $no_var = $value is cool. If you run it through pparen, it admits that mirabile visu it even precedents right: (($test_condition ? $yes_var : $no_var) = $value). Whoda thunk? - tchrist
[+6] [2008-12-30 23:49:26] sammich

Worst ever?

# TODO: Document This!

...exceptionally good when it's found at the top of every method declaration and at the top of the file.

(3) Well, at least it's an official TODO, so i don't think this is too bad. Of course, it ought to actually be done sometime later... - mafutrct
(3) //TODO: Maintain illusion that I'll care about this later - johnc
[+5] [2008-10-26 16:14:30] adrianh

I've been dealing with a large chunk of legacy code that's been written in bad Perl by somebody with a Unix shell background.

Because of the Unix background they've adopted the convention of using a zero return value as success. Everbody else in the Perl world this evaluates to false. Because of this you have variants of:

if (not $success ) {
  # happy path
} else {
  # failure

everywhere - mixed in with "normal" Perl libraries with the saner convention of false == failure, true == success.


Have a look in the linux kernel and its utility functions and you'll find they switch between 0 and 1 as success rather arbitrarily. It's painful to keep check of. - Henrik
(1) That's what SYMBOLIC_CONSTANTS are for. Thus if (cond == SUCCESS) is fine, but if (flag == true) is awful. - Loadmaster
[+5] [2010-08-16 19:14:33] Regent

Extra empty lines in the source code, especially in the very beginning or end of the method/class:

public bool HasSomething()

     int a = this.A + this.dA;
     // and other method's code here

     return false;


[+5] [2010-08-16 19:18:53] Regent

C#-specific: use of #region directive for a very small code blocks:

public class MyLittleClass
    #region Fields

    private bool _isSomethingLoaded;


    // The rest of the class

Seems to me you'd need at least two distinct blocks before you should use #region. - Loadmaster
[+5] [2010-09-15 03:36:19] sashang

Using ifdef...endif to 'branch' code from the main trunk

This rubbish:

#ifdef BUGFIX_1
   //some rubbish code
#ifdef BUGFIX_2
   //more garbage

This is rubbish for so many reasons:

  • Lack of readability. You can't easily tell which code path to follow.
  • Error prone when getting rid of the guards
  • Doesn't work with the toplevel makefiles
  • Makes code harder than it should be to manage.
  • Easy to create broken builds.

...and also a sign that they should be using source control, but aren't. - Steve Melnikoff
[+5] [2010-12-01 02:34:24] tchrist

¡uʍopəpᴉƨdn əpoɔ ƃuᴉpɐəᴚ

Having to stand on your head to read code:

sub main() {                                       sub 
    for my $input (reverse <>) {
        chomp $input;
        my    $ʇndʇno = uʍopəpᴉƨdn($input);
        say   $ʇndʇno;

[+5] [2010-07-08 21:19:04] Pangea

1) unnecessary javadoc for every instance variable and method. for e.g. see below

 * The logger instance.
private final Logger logger = Logger.getLogger(BasicCollector.class);

 * The collection backing this collector.
protected Collection collection;

 * The ordered list of sort criteria for this collector.
protected List sortCriteria;

2) passing the instance properties of the same class to instance below

class A
 B bRef;

void foo()

void bar(B anotherRef)

+1 for the first ( getColor(); /* returns the color; side effects: none; inparamater: void etc) - Viktor Sehr
[+5] [2010-06-25 13:42:50] kbok

Verbose naming conventions:

class Item {
    int idOfTheItem;

Mixing different languages:

String UserNomDeFamille;

Not to mention that Java allows UTF-8 in source code. You can see horrors like these:

public void SetDépart(Date départDate) {

(1) For the last one, it's called i18n (internationalization). What makes the English alphabet any better than other alphabets? I think we should use Chinese characters for everything--there are more Chinese than English people after all. This is more of a globalization problem in general. - Nelson Rothermel
I agree with you Nelson. But we should not mixed language. I wanted to code in french but it was easier to use getXxxx (lireXxxx, obtenirXxxx in french) SetXxxx (configurerXxxx ??? InitialiserXxxx in french ) So, once time I decided to code in english and comment in french. Some interesting point of view :… - Luc M
I'm always coding and commenting in english (german as mothertongue). Might be because I started out with VB, which is a very, very verbose language and it just broke the flow to code in german... Dim länge As Integer, Dim Unterfenster As Form = Hauptfenster.MDIChildren.Item(0) etc. *shudders* - Bobby
(1) +1 for the last one, here in sweden I've seen people use å, ä and ö (our special characters) in java. - Viktor Sehr
[+4] [2010-06-25 09:29:56] Brian Hooper

Naming functions 'consistently' by calling them...


[+4] [2010-06-30 15:24:58] Donal Fellows

The most frustrating style I ever encountered was a colleague's compiler. It was page upon page of code without any indentation whatsoever; every single line started in the left column so there were next to no visual cues. There were several hundred files like this:

IF (condition1
AND (condition2
OR condition3))
// some comment here

Maybe I'm exaggerating the number of files and lines, but not by much. (It was in a language called UFO[1], so I couldn't just automatically reindent without significant work to make an emacs mode to support that obscure language. The language had a number of other problems, including an implementation of strings based on unbalanced trees that was so boneheaded that it turned a fast compiler into something that ran slower than molasses in Antarctica.)

[1] I don't really remember that much about it other than what I've written above. What I do remember is that the code got rewritten in Java 1.0 and suddenly went enormously faster despite being theoretically less elegant.

BTW, the code was a compiler that had error correction that actually worked; it could recover from quite serious syntactic problems and still generate correct code. I believe that's pretty rare even now; my colleague was (and still is I think) a very good compiler theory guy. - Donal Fellows
Back in the ancient days, I ran into this using IBM FORTRAN. The problem is that in this scenario you have only the columns 7 thru 71 in which to put your code. Indenting was rare. - Dave
@Dave: Perhaps, but it sure wasn't a language restriction of UFO (and the guy sometimes used lines longer than 80 characters too). - Donal Fellows
IBM FORTRAN was especially restrictive. There was a hard limit in line length written into the system. The source code file type was defined as 80 characters per line and 80 characters per block. - Dave
@Dave: The code I was talking about was from about 14 years ago I suppose, wasn't in FORTRAN, was often more than 80 columns wide, and was thoroughly unreadable because the program in question was highly nested (even if unindented). - Donal Fellows
[+4] [2010-06-25 13:37:32] Tigraine

Blocks from people who are too much in love with Pascal:

if (condition == true) {
} //END IF condition == true)

(1) Hey, even Pascal lets you use boolean variables by themselves as conditional expressions. if (condition)... is perfectly valid Pascal. - Loadmaster
Sometimes this explicit variant bring some clarity, say if GetSynchronisedState() == true... - serhio
this can be helpful if code... is really long... but in general, yes it's annoying. - Brian Postow
(1) @serhio: Nope, whenever I see a single statement in an if I can assume that it returns a bool. However, for clarity that function should be renamed to IsSynchronised. - Bobby
if you're talking about putting a comment with the condition at the close brace, that can improve readability a bit when a long condition spans multiple screens, and matching open braces with close braces becomes a bit harder to do visually. that is to say, I do this. but only if i absolutely cannot possibly refactor the conditional block to be much shorter. - TokenMacGuy
(1) I am talking about the //END IF comment in the end. and to date I haven't found a reason why an if statement should be so long I can't fit it in one screen. If it gets longer, refactor or you're doomed anyway. - Tigraine
@Bobby: there is some readability difference between if (!Visible) and if (!GetSynchronisedState()) - serhio
[+4] [2010-06-17 22:42:25] Steve Sheldon

Functions laid out like this:

bool SomeMethod
   int arg1,
   int arg2,
   // some code

+1 it does get irritating if they use it for every single function. - Qwertie
(2) But it's good when calling the function and it has a boatload of arguments that you have to scroll horizontally for. This is especially true if the arguments are "long": bool SomeMethod(object.method().property1.property2, object2.property3.property4, object.method2().property5) - Nelson Rothermel
(1) I'm only using this if I have a hell of a argument list...on the other hand, maybe I should refactor that code. - Bobby
[+4] [2010-06-18 16:55:47] womp

Amazingly, my pet peeve coding style isn't listed here.

And that is - people who still format their code for 80 columns.

(6) Mine is the exact opposite. I do not know where you found a 3000 column screen, but mine is not that wide... - Kevin Panko
(2) It's not wider than 80 columns? Have you not upgraded your monitor since 1995? You can get bigger than a 15" terminal now. - womp
Go, wordwrap, go! - typeoneerror
Its not about the screen, its about printing the code on paper. - carleeto
(3) If you have to print the code on paper you are (probably) doing something wrong. - e.James
80 may be too narrow, but there is such a thing as too wide. Maybe 200 columns should be the upper limit, with the average line being under 100 columns. - Kevin Panko
(5) The screen may be wide enough but if wide text were readable, why are newspapers still printed in columns of 8 cm? Rhetorical question. 80-ish columns in code make sense. It’s not necessary to be dogmatic about it but deviating too much from it is plain unreadable. - Konrad Rudolph
@Konrad Rudolph - 120 columns is infinitely more readable than code statements split unnecessarily over multiple lines. Technology surmounted the 80 column limit well over a decade ago - people that still impose it are doing so for impractical and nostalgic reasons. - womp
@womp: I agree with 120 columns but this is a rather modest extension of the original 80 columns. That’s why I said that I’m not dogmatic. On the other hand, I don’t think splitting code statements over multiple lines is a problem at all. - Konrad Rudolph
(2) I like 80 col because it means that I can know that I can have two emacs frames visible next to each other and still see all the code... line wrapping is just bad. - Brian Postow
[+4] [2010-06-18 17:33:43] Qwertie

Microsoft STL code has horrible indentation. This is from <hash_map>, and the entire STL is written the same way. They also seem to rely on comments in lieu of good names for things (_Mfl? _Kty? _IReft?).

        // TEMPLATE CLASS _Hmap_traits
template<class _Kty,    // key type
    class _Ty,  // mapped type
    class _Tr,  // comparator predicate type
    class _Alloc,   // actual allocator type (should be value allocator)
    bool _Mfl>  // true if multiple equivalent keys are permitted
    class _Hmap_traits
        : public _STD _Container_base
    {   // traits required to make _Hash behave like a map
    typedef _Kty key_type;
    typedef _STD pair<const _Kty, _Ty> value_type;
    typedef _Tr key_compare;
    typedef typename _Alloc::template rebind<value_type>::other

    typedef typename allocator_type::pointer _ITptr;
    typedef typename allocator_type::reference _IReft;

        {   // make multi parameter visible as an enum constant
        _Multi = _Mfl};

        : comp()
        {   // construct with default comparator

    _Hmap_traits(const _Tr& _Traits)
        : comp(_Traits)
        {   // construct with specified comparator

    class value_compare
        : public _STD binary_function<value_type, value_type, bool>
        {   // functor for comparing two element values
        friend class _Hmap_traits<_Kty, _Ty, _Tr, _Alloc, _Mfl>;

        bool operator()(const value_type& _Left,
            const value_type& _Right) const
            {   // test if _Left precedes _Right by comparing just keys
            return (comp(_Left.first, _Right.first));

        value_compare(const key_compare& _Traits)
            : comp(_Traits)
            {   // construct with specified predicate

        key_compare comp;   // the comparator predicate for keys

    static const _Kty& _Kfn(const value_type& _Val)
        {   // extract key from element value
        return (_Val.first);

    _Tr comp;   // the comparator predicate for keys

yeah some of the dinkumware code makes my eyes bleed - Inverse
[+4] [2010-10-29 21:25:08] Mark

Using spaces instead of tabs for indentation. Yeah, I know it's contentious, but if we all use tabs, then everyone can see the code indented at their preferred width. If we use spaces, then it's up to whoever wrote the code originally.

But then you couldn't use tabs to align things (like variables in declarations or end-of-line comments) using tabs. Catch-22. - Loadmaster
(1) I use spaces to align those things... - Mark
[+4] [2010-10-30 00:40:53] jdizzle

Everyone writes a summary of their changes at the top of the file for every commit. It's especially funny because we use ClearCase and all of the bureaucracy built into it is completely ignored. That is, every checkout/checkin/commit/deliver message is empty.

[+4] [2010-12-01 02:31:40] tchrist

Staggered Indentation

Indentation for showing off public-vs-private in Java:

        private final static String
    boundary_after_not_word      = "(?="  + identifier_charclass + ")";

        private final static String
    not_boundary_after_word      = boundary_after_not_word;

public final static String
    precedes_word                = boundary_after_not_word;

        private final static String
    boundary_after_word          = "(?!"  + identifier_charclass + ")";

        private final static String
    not_boundary_after_not_word  = boundary_after_word;

public final static String
    not_precedes_word            = boundary_after_word;

        private final static String
    boundary_before_not_word     = "(?<=" + identifier_charclass + ")";

        private final static String
    not_boundary_before_word     = boundary_before_not_word;

public final static String
    follows_word                 = boundary_before_not_word;

        private final static String
    boundary_before_word         = "(?<!" + identifier_charclass + ")";

        private final static String
    not_boundary_before_not_word = boundary_before_word;

public final static String
    not_follows_word             = boundary_before_word;

[+4] [2010-10-01 13:44:24] dwell

OMG [1], I just saw this real example for declaring a variable:

gv_240407           TYPE c,                       "RM 24.04.07

gv_230507           TYPE c,                       "RM 23.05.07

gv_180208           TYPE c,                       "RM 18.02.08

gv_040308           TYPE c,                       "RM 04.03.08

gv_170408           TYPE c,                       "RM 17.04.08

So smart, isn't it ? Grrr


[+4] [2010-10-19 18:31:14] juls

Some more vertical alignment:

void    print_array     (   int const     *arr            ,
                            int const     size            );
void    unite_2_arrays  (   int const     *arr1           ,
                            int const     size1           ,
                            int const     *arr2           ,
                            int const     size2           ,
                            int           *arr_1_and_2    );

[+4] [2010-02-10 12:55:11] Bright010957

Using extra whitespace between code blocks like this:

public void doSomething()
   //Do something:

   int i = 0;


okay two blank lines is excessive, but you don't like whitespace in general? - Inverse
(2) What I really hate is a blank line after a line that only contains an open-brace, or before a line that only contains a close-brace... especially when there is NOT a blank line after the close-brace line. Makes it look like the close brace "belongs" to the thing that follows it, vs. the thing that precedes it. - Dan
@Inverse: "Using extra whitespace..." - Matthew Crumley
[+4] [2009-08-19 01:39:00] smcameron

camelCase. it'sUtterlyInexcusablyRetarded.SeeHow"Easy"ThatIsToRead.

(11) iWouldAgreeIfPeopleWroteCommentsInCamelCaseButTheyDoNot - lttlrck
And what would be the better alternative? - n1ckp
(7) Some_would_argue_that_underscores_are_no_better.Either_way_its_just_a_consistent_‌​method_of_marking_the_ends_of_words. - Kaji
Seeing my own reply also reminds me that camel case is less likely to have line break issues when viewing wrapped text - Kaji
strThisIsEven.worse(strIsntIt); - JCasso
_'s are a billion times easier to read. not perfect, but you have to choose some type of separator... - Inverse
(1) whataboutlowercaselettersstrungtogether? - Brendan Long
or.chaining.everything.into.several.extra.substructures? - e.James
[+4] [2010-03-29 21:08:30] adopilot

In TSQL code I do not like when placing inner join after the table

table1 inner join
table2 on

For me it is much easier to read code looks like this

from table1
inner join table2 on

That one drives me nuts too. - HLGEM
[+4] [2010-03-27 17:48:49] community_owned

Trying to make Visual Basic comments look like C, C++, C# comments, etc.:

'//My comment

'//My other comment

This kind of fall more in the 'making me laugh' category.

Next thing you know, those silly gooses will try to use curly brackets. - Jeff O
[+4] [2008-12-30 23:59:18] Logan Serman

Can't stand this:

if (condition) {
    # ...

Not sure why, either. I've always had a new line for braces. I also always keep a new line for return, so this also bothers me:

function a($x)
    $y = $x * $x;
    return $y;

I believe that's standard K&R style. I agree with you, that I like that way better, but it's a standard. - Brian Postow
Yea, I think eclipse uses that by default (or at least it used to) - SnOrfus
I don't use that style either, but if you can't deal with it, quit programming, because you are going to see it whether you like it or not. - finnw
Interesting note: in javascript these two styles can result in different outcomes because of implied semicolons - cobbal
This convention comes from VB to imitate the SUB/END block(Steve McConnel prefers the first style in his books Code Complete)... I hate this style too ! - Nicolas Dorier
(5) I think K&R well predate VB. - Xepoch
This is mine as well. +1 - Zachary
[+4] [2008-12-31 00:05:15] JB King

Macro-filled code where 99.9% of lines of code use at least one if not more macros making the code a language unto itself mostly.

I did have this with my first out of school job where this is what the server developer did that he thought was a good idea. It eventually got to be OK, but by then I had spent a couple of years in it and was the most senior employee that ran it.

Agreed. When you're on the outside looking in (don't understand the mini-language the macros create), code can be much harder to understand. When you've written a complex set of macros yourself, it's easy to rely on them. I think there's room for a middle ground--macros that are fairly self-evident. - Reuben
The frustration is the initial, "Now I get to learn another language," since the macros are used so frequently that there doesn't seem to be any of what the language is supposed to be as the macro overload or override everything. I left out the propietary markup language that went with it. - JB King
I second that. I've seen code that was "manually compressed" by substituting anything that repeats more than once with macros. - Ates Goral
(3) Using macros to tailor the language to suit the problem is not bad per se, it's just a pain when the macros operate on the text instead of the language. To be more clear: C preprocessor macros are of very limited use and prone to break, macros in Common Lisp are the best thing since assembler. - Svante
I worked with a guy who got tired of typing Request.Form and Request.QueryString so he wrote functions to mask them down to a single letter... - Scott
[+4] [2009-02-09 21:41:57] Brian Postow

I agree with most of the above: hatred of inconsistent indenting, bad variable names, etc. I also hate longer than 80 column lines. I like to have 2 open windows at a time, and always having them be 80col means that I know how big a line I'm working with.

Also: multiple statements on one line:

i = 3; j = 5; k = 8;

And for some reason, I can't stand indented braces:



(8) Get a wider monitor? Enforcing constraints on everybody for one person's code viewing style isn't very cooperative. Survey the team for how many characters fit on their screens, then use that. If they all use your system, fine, but 80 characters can kill readability of a lot of code. - Trampas Kirk
Who's enforcing constraints on whom? If they have 150 character long lines, in order for it to be readable, I have to have a 150 character wide window... Either way someone's forcing something on someone... - Brian Postow
Use it was an excude to get a nice 26in LCD monitor :) - Matthew Whited
Indented braces are evil. - Robert Harvey
Sometimes fitting a line or string literal into 80 chars is even uglier than just turning on word-wrap... - Inverse
Turn on word wrap or stop programming on a mainframe terminal :D - Jimmy
[+4] [2008-10-26 11:57:54] steffenj

Putting statements on multiple lines, especially when it's really not necessary, as in this case:

if (bOne &&
    bTwo &&
    bThree &&
    bFour &&
    (!bFive ||
   // do something

And it's even more ugly counterpart:

if (bOne
    && bTwo
    && bThree
    && bFour
    && (!bFive
    || !bSix))
   // do something

(7) This is subjective, so I'm not downvoting it, but I often do split if conditions like this, especially when there are six conditions like this example. - Zan Lynx
(2) I think what you ought to do is create a submethod and then call that method. The name of the method should be descriptive to tell a new developer what it is doing. - andHapp
I do this sometimes, especially if a nice, long, descriptive method or variable name is going to make the line more than 80 characters. - James Socol
If it's not necessary as stated, I agree, otherwise I have no problem with this. It's better than scrolling the IDE horizontally. - SnOrfus
(2) It's much better to wrap that whole condition in a meaningfully named variable, then get the value for it from a meaningfully named, unit testable method. - Trampas Kirk
I do this at times, especially if I suspect I'm going to be adding to or removing from the list while getting something worked out. - Kaji
I can see having one operand of the && operator per line, but it's definitely bad style to split lines on every operator. - Loadmaster
-1: if bTwo condition is long enough this is a necessity to write such a syntax. - serhio
[+4] [2009-03-03 20:59:52] Stuart Branham

I absolutely hate it when people don't format their SQL in a readable, consistent way. The "L" stands for language, people!

Also, why do people insist so strongly on ALL-CAPS'ing SQL code? It doesn't really serve any purpose I know of other than making it harder to read.

(10) I find the CAPS makes it easier to split out the keywords for when people or tools pullout your CRs. - Matthew Whited
(1) Agree @Matthew I prefer capitalized keywords - TokenMacGuy
Thankfully SQL isn't case-sensitive, and I find lowercase easier to read too. Putting keywords in capitals is a task for a pretty-printer, IMO. I think it then makes sense to use initial caps for identifiers (as we do in English for people, cities, and other important entities). - cheduardo
[+4] [2009-03-03 20:35:23] finnw

A former colleague of mine insisted on using getter and setter methods for all member variable access - inside the class that owns the variables.

And to make it worse he always made the getters & setters public, even when they didn't need to be.

(4) Using getters and setters even inside the class allows the use of mocked objects. And then they're really easy to write unit tests for. Public getters and setters allow you to modify those member variables for test purposes at run time. It's a GoodThing(tm). - Trampas Kirk
I don't agree. I'll be damned if I have to make a property for every single member variable. - Ed S.
(7) Sounds like madness to me - classes should only expose data that needs to be exposed. - Richard Ev
@cynoclast: isn't it better to use reflection? If every field has a getter and setter, even if not necessary, they are redundant and break encapsulation. Also, you ship part of test code, which is far from a good thing... - ya23
[+4] [2009-04-03 15:59:02] Mutant
public Collection getMappingsBySponsor(String Mgr, String spons)throws SQLException, ClassNotFoundException, Exception
    StringBuffer sql = new StringBuffer(this.INV_NAME) ;
    sql.append("= '") ;
    sql.append(Mgr) ;
    sql.append("' AND ") ;
    sql.append(this.NAME) ;
    sql.append("= '") ;
    sql.append(spons) ;
    sql.append("' ORDER BY ") ;
    sql.append(this.SHORT_NAME) ;

    return getAMappings(sql.toString()) ;

There are better ways to do it, and it was like all functions written with this kind of method.

[+4] [2009-04-16 15:24:45] cletus

In C/C++ I always did this:

if (a == b)
  // do stuff
  // do different stuff

Years of Java had it beaten out of me. Instead it's now:

if (a == b) {
  // do stuff
} else {
  // do different stuff

I've learnt to accept that and that's how I write my Java now.

What I absolutely cannot stand however, what absolutely drives me mental is this:

if (a == b) {
  // do stuff
else {
  // do different stuff

(4) Why? All three seem perfectly normal. - Brendan Long
Don't know for Java, but in .NET Visual Studio does auto-formatting, so keeping ) { will be difficult and usefulness. - serhio
I like using the third if I want to put a comment before the else. - Casey
@serhio: The auto-formatting in Visual Studio is highly customizable. I have it set so that it uses the format in the second example. - Ferruccio
@Ferruccio: customization is good. Like the black background "style" is customizable. I used the black background until understood that the eyes become more tired reading white letters on black background. So, each I believe the "defaults" colors and styles where an object of study for be like they are. And, secondly, your code style will be certainly different from your team. So, sometimes, I prefeer universal and standard to "customization" - spending energy to nothing. - serhio
[+3] [2009-04-03 16:52:18] kthakore

Joe Caldwell -MTG 2009


Rewrites all of swing because "its too slow" and "has no features"

So, he never used WinForms, hu? - Bobby
[+3] [2009-02-24 16:59:43] Xolve

Symbian C++ coding. Too many types of "strings". So many classes and it doesn't look like C++.

[+3] [2009-02-10 03:44:10] hasen j

The PHP programming language..


Once is fine, but when ever line in your code has a bunch of these it really breaks the flow for me. - Joel Coehoorn
Do you mean $a="variable"; $$a=10; echo $variale; // echo 10... If not, I don't get it. If yes, these varaibles may be very useful but should not be used at every sauce... - Luc M
(1) no, I mean languages that force you to use dollar signs for (certain) variables. - hasen j
(1) But it prevents collisions with reserved names! :) - Nelson Rothermel
That's not a coding style, it's a language rule. It's only style if it's optional. - Nate C-K
[+3] [2010-03-27 17:16:15] James McLeod

Variables/constants/classes with too much scope: global variables which should be local to a file, file scope which should be class scope, etc.

Leads to weird names to avoid naming collisions, and to maintenance nightmares.

[+3] [2010-03-27 17:22:58] Matt Huggins

Ehh, it's questionable if this response truly ties in to the question you're asking, but I'll offer it anyway. I hate when multiple users edit the same code in different IDE's such that the tab delimiters are different.

For example, one developer might use Eclipse, such that when he presses the TAB key, it inserts a single tab whitespace character. Another developer them might use vi, such that when he presses the TAB key, it inserts 2 single space whitespace characters.

This might look fine to the vi developer, assuming vi is set up to display tab characters such that they span 2 fixed width characters. However, Eclipse might have tab characters displaying such that it spans 4 fixed width characters, resulting in code appearing like this:

    if ($user->save()) {
    $email = EmailManager::generate('register', $user);
        $email->setSubject('Welcome to Example');

So frustrating!

I use visible whitespace, colored light-yellow-on-white, to spot these problems and avoid creating them in my own code. - Qwertie
[+3] [2010-03-28 03:04:06] MPelletier
  • Everything (functions, variables) declared global or public.
  • Functions that are over two pages long.
  • Code that is obviously copy-pasted.
  • Actual production code that has the "My-" prefix in a variable or function.


  • Implementation directly in an event function rather than in a helper function, and....
  • Firing an event from code to have its handler execute.

For these last two, allow me:

Suppose you have some C# for a menu item to print a document:

private void PrintMenuItem_Click(object sender, EventArgs e)
    //Code all the printing code here. Formatting, etc.

Then you need a button too. No problem, we already have that code!

private void PrintButton_Click(object sender, EventArgs e)
    PrintMenuItem_Click(sender, e);

Code that is obviously copy-pasted... you mean "multiplicated" or pasted from other sources that the project? - serhio
See - 1.3 million lines of code created this way - Dave
serhio: Code copy-pasted from other projects is not as bad as code copy-pasted (i.e. multiplicated) in the same project, multiple times. - MPelletier
How am I supposed to work with a class which only exposes properties and no functions? Or did I misunderstand you there? And I agree, global/public declared variables are...are...I just can't stand it. - Bobby
@Bobby: It doesn't work for all languages, but some (J for example) can be made to have several "classes" declare all their functions as global (not the same as public. Almost like a static call, only sans-base class). That leaves a mess of classes. Plus, even other mainstream languages (Java, C#), declare all your functions public all the time and you've created a damnable mess. - MPelletier
@MPelletier: That sounds like a mess, yes. - Bobby
[+3] [2010-03-29 19:59:23] Bill Martin

Session variable cowboy programming

Especially the kind that doesn't use method params but uses session objects as their own personal litter box.

public GetData()
  //blah variable from 5 pages ago. Could have been changed in previous pages.
  r = Session["blah"]
  var c = new HelperClass();
  var h = c.GetMoreData();

class HelperClass
  public string GetMoreData()
//no friggin idea where mm or n is set. Generally changed in class instance. 
       return Session["n"].ToString + Session["mm"].ToString

Just worked on a project like this and lost some more hair..

That's horrible! - e.James
[+3] [2009-08-19 01:22:20] João

In Java, prefixing variable names with m_ and s_ to distinguish between member and static class variables. Every modern IDE allows you to differentiate them.

In VB a underscore is needed, because the var names are case insensitive. - serhio
[+3] [2010-01-13 22:51:06] Jack Marchetti

It drives me absolutely crazy when someone does this:

if ( /* condition */ ) { /* proceed to do your code in this same line */ } else { /* other code, also in this same line */ }

Perhaps this is fine for some people, but I have to have my resolution very low due to poor eye sight and having to scroll to see the entire if statement makes me want to quit sometimes.

Especially when they don't put a space after the if - Inverse
Isn't setting your resolution low the incorrect way to resolve this? Shouldn't you use a proper resolution and increase the font display size on everything instead? - Chris Marisic
@Chris - you would think. Anytime I've tried that, it just doesn't look right to me. Windows 7 has improved, but it still doesn't work for me. I love how Mac handles zooming, but I only have a Mac at work. - Jack Marchetti
Good thing big monitors are cheaper nowadays. - Qwertie
big monitors usually only look right at very high res, and my blind arse can't do high res. ha - Jack Marchetti
[+3] [2010-01-13 23:19:09] Loadmaster

Code with little or no comments.

I've worked on far too many projects that had zero comments. Creative laziness is a virtue, but slothful laziness is unforgivable.

This is not a style per se, but more of an illness.

(1) If the code is self-explaining then there's nothing wrong with no comments, imho. - Bobby
(1) Self-documenting code is a myth. Anything more complicated than a simple increment statement needs some explanation, even if it's only to establish the context of why it's doing what it's doing. - Loadmaster
[+3] [2010-01-13 23:47:05] Chetan Sastry

Too much safety against NullReference exception or check for null before doing anything with ANY variable:

if (foo != null) {

What if foo is null? Where is the condition to handle that?? Bothers the hell out of me. Imagine a missile launch control system coded this way:

if (missile != null) {
    if (targetPackage != null) {

And you might well ask, how did foo get to be null there? Why catch that condition in that place and not in some other. - Permaquid
Totally agree, funny that you got -1s - flq
[+3] [2010-02-10 12:57:37] Roland Bouman

Right aligned SQL:

    SELECT emp.*, dept.*
      FROM employee emp,
           department dept
     WHERE emp.dept_key = dept.dept_key
       AND = 'Y' 

SQL with capital identifiers:




ANSI SQL Quoted identifiers

    SELECT "EMP".*, "DEPT".*
           "DEPARTMENT" "DEPT",

MySQL quoted identifiers:

    SELECT `EMP`.*, `DEPT`.*
           `DEPARTMENT` `DEPT`,

Using the double quote as string delimiter in MySQL:

    SELECT "I just love C strings too much to give up on my double quotes";

[+3] [2010-02-10 11:53:01] odiseh

Or this one:


Print() function must be written after the if else block.

(3) That's actually code duplication, not a question of style, but a wrong principle. - kahoon
[+3] [2010-08-09 08:39:38] infernoz

Writing C style code in Java, and not making proper use of the more advanced Java data structures, I/O and currency support provided with Java, like the Collections, NIO and the Concurrency classes.

Arrays are fine, up to a point, but can make algorithms harder to write correctly, standard I/O can less inefficient for file transfer than file channels (e.g. Guava file transfer code), and plenty of synchronized/Thread based code is less safe and efficient than Concurrency classes.

corollary: writing java style code in C... - TokenMacGuy
[+3] [2010-08-16 19:23:46] Chris Lively

The worst I've seen is Yours...

(5) Code is like fart. You can only smell yours. :-) - Luc M
[+3] [2010-07-01 04:23:11] sashang

Redundant comment headers, like the name of a the file in the comment.

// ******************************************************************************
// PROJECT:      name of proj
// MODULE:       Name of module
// FILE:
// AUTHOR:       Me
// DATE WRITTEN: the date I started writing this tome.

(3) Having the source file name is useful if you are used to looking at paper printouts or sending the source via email. These kids today, I tell ya... - Loadmaster
(1) @Loadmaster: If you have to email or print code you're doing something wrong elsewhere in your process. There's no reason to mandate ridiculous redundant comment headers like this. - sashang
What about open source code available on web sites? - Loadmaster
@Loadmaster: Not sure what you are getting at. I had a look at the linux kernel and I could find examples of files that had the filename in header comment and files that didn't. It's certainly not mandated. Also I suspect that its only the older files, the ones in existence prior to version control being used, that had the filename in the header comment. Newer files don't. And besides the project I'm working on isn't available on websites. If it were people would laugh so hard and wouldn't be short of jokes. - sashang
If you are sharing code over the internet, especially for open source, you should only be sharing it in the form of a source repository (git clone git:bla bla bla) which does an exceptionally good job of passing the filename along with the file. - TokenMacGuy
[+2] [2010-06-18 16:44:47] Dave

Making each programming statement one line, regardless of how complex the logic of the statement or the length of the statement.

[+2] [2010-06-25 08:37:54] serhio
  • Mixing of languages:


  • Abbreviations:


  • Hungarian*:


*however I accept Hungarian for Controls à la btnMyButton

  • Long ones


MyClass.cmbAgent.Init(cnnSQL, objColDefCollection, Infragistics.Win.UltraWinGrid.AllowAddNew.No, Infragistics.Win.DefaultableBoolean.False, Infragistics.Win.DefaultableBoolean.False, Infragistics.Win.UltraWinGrid.SelectType.Single, "NAME", , MyClass._Formulaireappelant, MyClass._Traduction)

[+2] [2010-10-29 19:11:39] brian

When my boss, who 'used' to write code, tells me (who does), how to write code.

I guess it depends: did he write code 2 years ago, or 20 years ago? - Nate C-K
[+2] [2010-09-15 04:40:48] vlad003

Python code indented only 2 spaces.

I guess those people hate that Python forces indentation; but just accept it if you use the language. 4 space indents are much more readable. Just set your editor to that and hit tab.

A really short script is OK (I guess) but when it's a 2,000 line file, it's a nightmare to try to read.

[+1] [2010-12-19 04:11:45] Vargeux

Indentation fail

I know someone who indent his code like this


It looks like he is coding without knowing what he's doing.

And one of the teachers of my college indent his else-if like this

    else if(){
        else if(){
            //then this
            else if(){ 

Horrible Java teacher.

[+1] [2011-01-15 16:51:24] Hoàng Long

Not actually frustrating, but it's a little hard to read. Here's some side effect of what we call "dynamic programming".

In groovy & grails:

// function in controller class
def helloSir = {
  "Hello, sir"

def helloMadam = {
  "Hello, madam"


// call in controller
def test = {
   def input = "Madam"
   render ("hello" + input)()

Result: "Hello, madam"

It works.

[+1] [2010-06-30 14:25:54] andyortlieb

PHP with lots of sporadic include's and iframes.

[+1] [2010-06-30 14:31:14] Matteo Mosca

Lots of things:

  • Spaghetti coding
  • Putting data access logic and/or business logic in UI button click handlers
  • Programming on concrete stuff instead of interfaces
  • Copying and pasting code all around instead of creating reusable modules
  • Sticking to 10 year old technologies and refusing to keep up with modern stuff (still using datasets and refusing to learn LINQ and any ORM technology like EF [1] or LINQ to SQL [2])

This is just a small portion of the stuff I can't stand, and all of this, and more, is regularly done by my only colleague.


Copying and pasting is the one that really makes me angry. I've spent untold hours cleaning up old code that was created in that fashion. At my last job I discovered 6 different functions to generate the SQL code to create a table in Oracle in slightly different ways, all written by the same guy. (These were fairly complex functions that dealt with partitioning, etc.) - Nate C-K
[0] [2010-06-18 17:35:51] MSN

Monolithic design.

[0] [2008-10-26 11:53:51] Yarik

This one is specific to VB... I really hate multi-line statements - one of those legitimate features that should not be used. For example:

ErrorMessage = "Lorem ipsum dolor sit amet, " _
             & "consectetuer adipiscing elit. " _
             & "Donec pharetra arcu et urna. " _
             & "Vivamus vehicula leo in dui."

Of course, the main problem is not those underscores and not ampersands at the beginnings of the lines. They are eyesores, but the main problem is inability to comment one of those lines...

Luckily, underscores will be deprecated soon:… - Mauricio Scheffer
(7) For error messages- yeah that's a pain. But just wait until you have to keep a large sql statement string in code. - Joel Coehoorn funny. - JCasso
(1) I realise now how terribly evil it would be to have a block of lipsum show up in an error message... :) - MPelletier
(1) Being able to see the full statement in one screenshot, without having to use my double wide monitors, makes it easier to maintain. - Dave
(5) 80 columns, baby, 80 columns. - Loadmaster
[-1] [2009-05-30 22:43:12] Alex

In C#, using static readonly instead of const for absolutely no reason. Seen many times. Does static readonly look cooler, somehow?!

(1) I'm guessing it's people misunderstanding the fact that const only works for values available at compile time, so they get burnt once and stick to using static readonly everywhere. - Mark Simpson
(4) On the other hand, readonly is better for maintainability, as it is not "burded" in client code. Bill Wagner advocates for using readonly instead of const in his book "Effective C#". - Philippe
It is a Java habbit. There are no equivalents to const in Java. Thus using final (mostly static final) is the only way. Since readonly is the C# equivalent of final keyword, developers migrated from Java use static readonly anywhere. I know because i did this :) - JCasso
(7) readonly means that other DLLs get the value at run-time, so they do not need to be recompiled if the value changes. Arguably, use const only if you are certain it will never change. - Qwertie
[-2] [2010-06-17 22:58:54] Matt Greer

I'm not one for SESE at all, but this style bothers me when there is only one condition to check:

void Foo(bool bar)

    // rest of the method

I much prefer this:

void Foo(bool bar)

        // rest of method


(10) this is used to reduce nesting and removes arrow head anti pattern - Sergey Mirvoda
(13) I much like Pattern 1 with return. - Svisstack
I've actually asked that question and it seems like the first one is preferred...though, I still don't like excessive use of return. - Bobby
I much prefer the first pattern. The second one leaves the if's } to be lost in the noise. - Mark
[-3] [2010-09-15 04:06:18] ring0

Languages that force the programmer to insert braces {} after anything like if, while, for... are pretty frustrating (e.g. Perl) when only one statement follows.

Especially for people coming from C, C++.

The programmer should be given the choice to insert or no the {} braces when she estimates that being relevant.

(3) I have to disagree. Omitting braces in if and for statements, etc, in C can lead to bugs if lines are subsequently added without inserting braces, and is prohibited by some coding standards (e.g. MISRA-C). - Steve Melnikoff
(1) Never had a problem with that, in 30 programming years. Again, choice is to be given to the programmer - if he deserves to be a "programmer". - ring0
Unfortunately, I can't choose to not have other programmers screw things up. I fixed a bug caused by omitted braces in Java code just this week. - Nate C-K
[-4] [2010-03-30 14:08:10] MPelletier

I'm not sure I've seen this one listed, but this "style" is aggravating: Essentially, calling a function, then checking some value not changed by the function, only to realize that the initial function was not the right one to call, so call another after:

int foo = bar();

if (snafu)
    foo = bar2();

instead of:

int foo;

if (snafu)
    foo = bar2();
    foo = bar();

(12) What about int foo = snafu() == 1 ? bar2() : bar();? - Mark
(2) @Mark: bad readability. - serhio
@Mark: debatable. It depends. But the thing I wanted to highlight is executing a function, then checking some value just to say "oops, guess I should have run foo2". Shows careless patchwork. - MPelletier
[-6] [2009-05-10 16:31:30] Viktor Sehr

I really hate it when people create functions for simple procedures within classes;

private int getMaxValue(){
    return *std::max(m_values.begin(), m_values.end());

private someFunction(){
    int value = this->getMaxValue();
    value *=-1;

or something like;

void createAndAddOpenButton(){
m_openButton = new JButton();


(9) If the little function is called more than once, it make maintenance easier/more reliable in case the little function changes. - Qwertie
[-6] [2009-03-03 22:19:39] Jeff

I agree with some of the other posters. Renaming variables is just a waste of time.

Here's an example in PHP:

$user_details = mysql_fetch_assoc($user_details_query);

$firstname = $user_details['firstname'];
$lastname = $user_details['lastname'];
$email = $user_details['email'];
$phone = $user_details['phone'];

Surprisingly I've seen several programmers code this way. It baffles me that they can't use array variables.

(8) I do this all the time (although I never use PHP). Saves you from nasty typos where you spell 'email' wrong the 10th time you use it. - erikkallen
(1) echo "$firstname $lastname"; Is easier than echo $user_details['firstname'].' '.$user_details['lastname'] because i think this did not work: echo "$user_details['firstname'] $user_details['lastname']"; - Tarion
I think PHP has a function to automatically expand arrays to variables like this. It might be list() - Macha
I've seen this pattern in deeply nested loops to reduce the number of hash lookups. This can be a noticeable speed improvement. Basically useless in other contexts, though. - TokenMacGuy
@Macha, list() or extract() would do that, but I wouldn't recommend doing so. - John McCollum
I use this with $_POST and $_GET variables to extract the data and make it easier to manage. $username is far easier to retype than $_POST[username], and you don't have to worry about problems using it inline in strings, either. - Kaji
if you do not use $firstname = $user_details['firstname']; then you will need to use $first_name = "firstname" and then use $user_details[$first_name] in your code. It is not only about typos. What are you going to do if someone change table field names? How to refactor? - JCasso
In PHP you can always abbreviate this whole set-var-<X>-to-value-of-array-value-at-key-<X> with foreach($arr as $k=>$v) $$k=$v;. Just kidding ;-) - Frunsi
@Tarion - you can do "{$user_details['firstname']} {$user_details['lastname']}" - Matt Huggins
It may be faster (?) since you only have to search the array once. - Nelson Rothermel
I know your example is in PHP, but in strongly typed languages then it makes more sense to do that. I feel that it's less strongly typed if it requires a string to access a particular object. - Corey Ogburn
[-7] [2009-04-03 16:49:58] e.James

Using undescriptive short-hand names for the arguments to main:

int main (int argc, char *argv[])

I always make them fully descriptive:

int main (int argumentCount, char *argumentList[])

(23) Why? This is convention, everyone understands what argc and argv mean and do. Why break that? - Jasper Bekkers
(4) I don't see any reason to maintain a convention simply because it is a convention. I think descriptive variable names are good coding style, so I apply them consistently. - e.James
(2) @Jasper: Not everyone does. Ask any coder when they see it the first time. @eJames: I agree. I don't think the source code saving C-style naming of "argc" "argv" is worth the loss of readability. Sure most people who have done any C will recognize them and won't have any trouble, but if you ask me, it's cruft from a byte saving era we no longer need. - Trampas Kirk
(6) I disagree with this instance. If you don't already know what they do and how they work, descriptive names probably wont help you terribly much. - TokenMacGuy
(11) In general the advice is good, but I think for main you are causing more of a mental speed-bump because everyone knows what argc and argv do and how to use them. - Brian R. Bondy
(1) @Brian R. Bondy: That is a good point. I've spent the last ten minutes trying to summarize my point of view here, and I'm very much on the fence. Any new applications have an almost inconsequentially small main function anyway (the actual argument parsing being done by some higher-level class, function or library), so the issue is almost moot. Really, the only place that I type code into a main function is here on SO. Given that I expect my audience to have some programming experience, I think I will have to concede your point. Thank you for the reality check! - e.James
If you were griping against the 'ac, av' names that I've seen, then I'd be with you. But 'argc, argv' are so normal that you are flying against convention. - Jonathan Leffler
I feel for you James, viva la newbie! - Qwertie
Thanks, Qwertie. For the record, I still think argc and argv are atrocious variable names. Were it not for the long-standing convention, there would be no excuse for using them in modern code. - e.James
(1) argc and argv are the convention. That makes them easy to understand and acceptable, the same way i and j are good names for index variables but too short for almost anything else. - Ben Gartner
[-9] [2010-03-27 16:47:05] Ben Shelock



Should be...


(13) -1 for the "should be" - hasen j
you "should be" a Java man... - serhio
(2) +1 for should be - Viktor Sehr
(13 * -1) + (2 * +1) != -7 Come on people. Be consistent with your votes. - quasiverse
[-10] [2010-03-29 20:20:26] Frunsi

Switch statement extra indentation. Microsoft Visual C++ typing "whatever-it-is-called" tools lead to that extra indentation, Emacs/XEmacs does not do this, and IMHO this is superfluous indentation without any significance. Though, I may be biased from many programming hours spent in front of Emacs/XEmacs some years ago...


switch( foo ) {
    case kFoo:
    case kBar:


switch( foo ) {
case kFoo:
case kBar:

I know, some people may disagree, but IMHO a switch is a switch, it is no conditional and it is no loop construct. That unnecessary indentation just helps monitor vendors to increase their sales numbers.

(18) I actually feel the opposite about this. Your "GOOD" example drives me nuts. - Daenyth
I like frunsi's style but I'd say get used to the "BAD", it's not going away. - Qwertie
(4) The so-called "BAD" method is much easier to follow due to the expected indentation that come with brackets. - Matt Huggins
When there is a "sub-block", then the programmer must have the freedom to add something to the "sub-block"! But in this case, the programmer is "not allowed" (!) to add anything outside of a "case" of "default" block/label. So in my world, a "case" statement is a block in every case, the enclosing switch block is superfluous (except the expression in the switch itself, which is not superfluous) and so the switch does not qualify as a block-requiring element. But that's just my view... - Frunsi
And a superfluous block is just superfluous! And that is true as long as someone proves me that black is white. Harhar, LOL, bla bla, laughing.. maybe someone will mention duff's device to disprove my statement? I suspect that someone dares.. however, duff's device would disprove my assumption. But you see, nobody uses it anyway ;-) - Frunsi
So, in summary: if your learned the style that your IDE (visual c++, netbeans, eclipse, whatever..) teached you: stay with that style. But the day will come, when you will start to think about that extra indentation (you can't insert your own code on that extra indentation level, between "switch" and outside of any "case", right?). Maybe you won't find a reason, but maybe you'll learn to know duff's device, and maybe you will be enlightened! :) - Frunsi
Visual Stuio autoformatting rullez... and unifies, so Microsoft people should not agree. - serhio
Actually switch statements are conditionals. See… listed along with 'if statements'. Also it's normal to indent after the scope delimiter operators (i.e. the { and }). This is something your 'GOOD' example fails to do. - sashang
You must be the developer who works on every project before I get a hold of it... With the style nobody likes... - Corey Ogburn
[-13] [2009-11-03 19:34:09] Wells

Ternary operators of any kind.

(31) this oft-repeated mantra normally originates with people that don't understand them, or the benefits. - lttlrck
(3) ternary operators are great! e.g. it is simpler to use ternary operators than building extra "control flow statements" around simple arithmetic expressions. even standard math notation has an analogue to a ternary operator!!! - Frunsi
OF ANY KIND? Come now, don't deny me my a !%! b <%> c operator! - Qwertie
@Hapalibashi: Well, of course it's repeated by people who don't understand the benefits! I DO understand how they work. And in limited cases they are ok, but in the vast majority of cases where I've seen them used they were excessive, and made the code much more difficult to read. - Brian Postow
Thanks for the votes. I met sooo many 3-ops haters... - ring0