views:

28118

answers:

111

When I asked this question I got almost always a definite yes you should have coding standards.

What was the strangest coding standard rule that you were ever forced to follow?

And by strangest I mean funniest, or worst, or just plain odd.

In each answer, please mention which language, what your team size was, and which ill effects it caused you and your team.

+290  A: 

Maybe not the most outlandish one you'll get, but I really really hate when I have to preface database table names with 'tbl'

Galwegian
or postfix them with _t !
Adrian
Isn't this just hungarian notation for DB's?
ARKBAN
Isn't that like prefixing variables with var?
Brian R. Bondy
The MS shop I used to work for enforced that one. Quite a bad habit to break now...and it's everywhere I go so you kinda need to comply.
Kev
If remember correctly one of the _very few_ keyboard shortcuts sql server had was to type the first letter of the table name to get to that table in the list; the first AND ONLY THE FIRST letter
MDCore
"Systems" Hungarian to be precise.
_ande_turner_
In a similar vein, I hate when ID columns in databases are prefixed with the table name, like in the product table there'd be a productid column. Redundancy that sometimes makes scripting without an ORM more of a headache than it needs to be
Andrew Ingram
I actually prefer the ID column to be prefixed with the table name. Makes writing queries a bit easier. And for foreign keys you can have the foreign key field the same as the key field.
Craig
I guess when refering to generic database objects, seeing a "tbl" prefix can immediately identify as a table instead of querying for its actual object type in a system table.BUT, who does that kind of low-level database operation anyway? ;-)
icelava
You might get the table confused though! With a girraffe.
pzycoman
On a similar note, I hate it when table names must be singular. My instinct is to name a table that holds, say, customers, "Customers", not "Customer". Sounds minor, till you realize all the trouble you would save if only you could name your table "Transactions" instead of "[Transaction]".
Atario
This seems like the smallest problem in the world to me. lol
Tommy
yikes, that's rough. and redundant
thomasrutter
I like when the ID columns for all tables are called RecordID this way it makes everything very consistent. Its my preference but when you write a query with joins there is no need to look up columns to see what the names are.
Lukasz
how about prefixing column names with the table name... CUSTOMER.CUSTOMER_REFID... now imagine the references to other tables
Newtopian
@Atario Sounds to me like you need to try Ruby On Rails. Google it; it's awesome.
Robert Massaioli
how about prefixing stored procedures with 'pra'
Nat
I do databases all day every day and I definitely prefer that the id column of each table contain the table name as part of the column name (eg "productid" instead of "id). I find it makes even moderately complex queries easier to read and gives a more usable set of default column names in the result set.
Larry Lustig
+372  A: 

I hate it when the use of multiple returns is banned.

Simon Johnson
People actually enforce that? lol.
Brian R. Bondy
Yes they enforce. At my current project there is a special rule in Checkstyle that flags multiple returns. I would vote this more than once if just I had more votes.
smink
What is the supposed point of this rule? Personally I'd fail a code review for code that could be made easier to read by putting in another return.
Mark Baker
From my experience, methods with one single return point tend to be less error prone, as that rule makes it easier for people to analyse the program execution.
Guido
On the other hand, eliminating an option at the beginning like "if(param == null) return null" can clean up your code quite a bit, to prohibit this instead of encourage it is somewhat criminal.
Bill K
I think multiple returns are fine up until a certain complexity and that's how it should remain a judgment call on code clarity like always
PeteT
Workaround:if (!Initialize()) { RetVal=ERR_BADINIT; goto ReturnPoint;}(lots more code)ReturnPoint: return RetVal;}Problem solved! ;)
Marc Bernier
Up until recently, multiple returns were banned. Then the fact this was a leftover from C, rendered obsolete by C++ RAII and functions with size less than 15 lines, was revealed. Since then, like Braveheart: "FREEDOM !!!!" ... :-p ...
paercebal
Using one exit point should be encouraged, but certainly NOT being enforced. Especially if you consider early-out conditions.
steffenj
The main reason for having one return point is to simplify testing of execution paths. Returns to shortcut execution can be misused. Even a single return inside a loop dramatically increases the test surface. It's easier to simply say 'one return point' without knowing why.
Robert P
Simply put multiple returns increase testing complexity. Further it increases the likelihood that you've done something wrong
Chris Lively
The real rule is that you should always return where you came from (instead of GOTOing). It doesn't matter how many returns you have as long as they're returns. This ban rule is a fundamental misunderstanding from people who apparently think they're programming in BASIC.
Kyralessa
multiple returns (except for an initial error check) are the sign of poor programming and made code very complicated very quickly.
Tim
I don't like multiple returns either. I think it usually shows that your method is probably doing too much. However, I wouldn't dream of a totally banning it. WTF? If you distrust 'your' devs that much, hire new ones.
IainMH
I think the real problem is a case of throwing the baby out with the bathwater. Early returns from bailouts are a good thing and it's sometimes quite reasonable to end a routine with a conditional where the paths simply are returns. Most any other case should be avoided.
Loren Pechtel
Hard and fast rules like this break my heart. Sometimes it makes sense, sometimes it doesn't. If it doesn't don't use it. While I have preferences I don't BAN anything. If I need to use "goto" I'll use it . . . it's just so far I haven't needed it (thank Jebus).
Binary Worrier
Your choice: multiple returns or more nested if statements. I'll take multiple returns.
Lance Fisher
I think *discouraging* multiple returns is a reasonable principle but, like others say, the nesting can get horrific if you ban it completely.
cletus
For most functions I think it's appropiate to once you have decided further execution of a function is impossible, you return/signal error. Makes the rest of the function less nested and easier to follow.It's like pre-conditions.
Tommy
Bah! this is nonsense up with which I will not put! Multiple return statements can be elegant. How would you do a nice switch..case blocks without them? Multiple breaks instead? They're not all that different than return statements.
thomasrutter
@thomasrutter - Agree 100%, if you can bail out early of a function that does heavy lifting, why not give your program that extra bit of efficiency? multiple returns allows this...
alex
Given the choice I would ususally prefer to litter my code with dozens if not hundreds of "if retcode" than return early especially when synchronization objects, memory or network connections are invovled. An outright ban is stupid but if it prevents people from committing even dumber mistakes WRT resource management than so be it. I can give a crap less about overhead, thats what the CPUs branch cache is for. Quality is much more important than either developer comfort or a few extra CPU cycles.
Einstein
Assuming that the single return version handles the same inputs, then testing won't be significantly easier. You still need to see that the function handles NULL, after all; you just happen to know that the function doesn't use an extra return to do so.
Max Lybbert
I've seen this before. Generally the argument is that blocks should have "only one exit point". However, blocks *do* have only one exit point, unless you use gotos or exceptions. They might have more than one path to get to that point, but if you don't like that you need to ban "if" and "for" statements as well.
T.E.D.
I don't understand it either.
fastcodejava
This one is simple. Multiple returns => good choice for small functions, bad choice for gigantic ones. So - it's more about writing gigantic procedural code. That's the real cause what should be banned.
Arnis L.
**For all those trying to figure this out** : it is a micro-optimization intended to increase speed slightly due to NRVO; like all micro-optimizations, it should not be used except at extreme bottlenecks. See the second half of http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement/85911#85911
BlueRaja - Danny Pflughoeft
Does this imply it's forbidden to throw exceptions too? Throwing an exception can also be seen as a return point...
Vinz
Doesn't recursion require at least two returns?Are they are banning recursion?
Fredrick Pennachi
I don't understand where this pro / anti multiple returns thing has come from - its a completely arbitrary choice (my preference is with a single return statement)
Kragen
If you want to debate this issue, don't comment here - go over to "Should a function have only one return statement?" http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement
Anthony
@AsLanFromNarnia: Recursion requires at least two branches, not two returns. You can always have a local variable to store the return value and have one return statement at the end.
Space_C0wb0y
@Space_C0wb0y That's true, good catch - I think I must have been taking crazy pills! :)
Fredrick Pennachi
+221  A: 

Almost any kind of hungarian notation.

The problem with hungarian notation is that it is very often misunderstood. The original idea was to prefix the variable so that the meaning was clear. For example:

int appCount = 0; // Number of apples.
int pearCount = 0; // Number of pears.

But most people use it to determine the type.

int iAppleCount = 0; // Number of apples.
int iPearCount = 0;  // Number of pears.

This is confusing, because although both numbers are integers, everybody knows, you can't compare apples with pears.

Gamecat
Wow, this was the fastest frustration to reputation function I ever saw.
Gamecat
Looks like we were about 19 seconds apart, big negatory vote for Hungarian.
vfilby
Yup sorry for that.
Gamecat
See this Joel on Software post about how *proper* use of Hungarian notation can help reduce bugs: http://www.joelonsoftware.com/articles/Wrong.html
flicken
Of course by using C++ instead of C you can write code so that the compiler gives you an error when comparing apples to pears.
Andreas Magnusson
Yes, Joel got it right. I wish compilers could be made to enforce Joel's version of it.
Loren Pechtel
Hungarian notation is still valuable for languages which don't enforce types - JavaScript is the big one.
annakata
True, but you can better focus on the real world type not the system type.
Gamecat
Shouldn't that be "int cntApples = 0; int cntPeas = 0;"? Ie. The prefix is the variable "kind".
Blorgbeard
No, else you are "allowed" to compare them together. Although you have a point on that the prefix should include both fruit type and count so appcntInMyBasket is probably better.
Gamecat
I read a story that hungarian notation was originally used to tell whether a variable contained validated data. `uInput` was unchecked user input, `sInput` contained checked input. This use is actually very useful.
Svante
Shouldn't that be "Number of peas"?
chryss
App hungarian would name these variables cApple and cPear, for "count of apples; count of pears"
Jacob
@chryss: No, it's not a typo. "app" and "pea" are intended to mark the count variables to be of the type/kind "apple" or "pear". That was the original intention of the original (=good) hungarion notation.
DR
At least the first one is correct ... everything with "Apple" in it needs to be prefixed with "i". ;)
jellybean
@jellybean, LOL.
Gamecat
The way you are using Hungarian makes very little sense to me. SEe, you CAN add the number of apples you have to the number of peas you have to end up with the number of apples and peas you have.
Jasper
The microsoft coders who wrote the Win16/Win32 API and SDK popularized this hungarian-is-for-c-typing-info approach, which is SO wrong to make a general coding standard.
Warren P
+36  A: 

Hungarian notation in general.

vfilby
Well, I like H/N for control on a page. It's much easier to find all the textbox controls in an IntelliSense dropdown when all I have to look for is txtFooBar.
cciotti
If you've got that many controls on a page that you have to find them by type, you've got bigger usability problems.
Roger Lipscombe
HUngarian notation is not evil, just need to be used properly http://www.joelonsoftware.com/articles/Wrong.html
Czimi
I will concede with respect to controls. Then Hungarian notation can be helpful. In general though, I think Hungarian notation is obsolete, and generally misused. It has drifted from it's original intention.
vfilby
Horribly misused, yes. Wrong, no.
Loren Pechtel
A lot of people start an interface name with an I, IEnumerable, IList... In .Net framework al the interfaces start with an I.
tuinstoel
+1  A: 

Use _ or m_ in front of global variable when you can simply use the keyword this. when you need to access global variable...

Daok
Uh? Isn't "m_" more commonly used to identify members, not globals?
unwind
Do not know, not me that enforce that! m_ for module... module... class.. I can't tell you more :P
Daok
This is part of "How to write unmaintainable code" -- you can use m_ for module, member, and method.
ARKBAN
_ for private instance member isn't bad...m_ irks me though.
Kev
I use m_ for all variables, functions, modules and filenames it means "mine"!
Martin Beckett
I've grown fond of _varName for private class variables, VarName for accessors, and varName for function parameters and local variables. It gives me a quick visual identifier as to scope.
toast
the catch, I think, is that the compiler will enforce the use of "m_" (or whatever other prefix you choose), but the "this->" is optional, and so might be overlooked.
glamdringlfo
+1. Great arguments, guys! Where were you when I asked precisely that question ? ;-) http://stackoverflow.com/questions/132777/do-you-prefix-your-instance-variable-with-this-in-java
VonC
I don't use leading underscores. They're safe provided they're followed by lowercase letters and in some sort of class or namespace, but it seems easier just to avoid them.
David Thornley
+3  A: 

Anything having to do with formatting (especially place of '{' and other block character) is always a pain to enforce.

Even with an automatic format at each source file checking, you can not be sure every developer will ever always use the same formatter, with the same formatting set of rules...

And then you have to merge those files back to trunk. And you commit suicide ;)

VonC
Note: the location of the { matters in Javascript :-(
Frew
@Frew: that would mean the location of curly brackets have to be *enforced* consistently by every developer. That would not be harmful for merges.
VonC
+5  A: 

In Delphi we had to change from

if something then
begin
  ...
end
else
begin
 ...
end;

to

if something then begin
  ...
end else begin
 ...
end;

in a project with 1.5 million lines of code. Imagine how easy this was on source control, diff, and merge! It also led to forgetting begin and not noticing it right away when the compiler announced a superflous end.

Ralph Rickenbach
Fortunately there are great code formatters for Delphi.
Gamecat
Well, we were using one at the time, but the rules were changed in maintenance phase...
Ralph Rickenbach
+67  A: 

Not being able to use Reflection as the manager claimed it involved too much 'magic'.

leppie
Yeah, magic is hard to maintain, appearantly ;) LOL, though.
Rik
That's probably the right rule, for the wrong reasons :)
Bobby Jack
for 'magic' read performance killing unmaintainable obscure nightmare code. He's right.
gbjbaanb
Reflection does tend to cause nightmare stack traces, which is my main objection. I'm not too bothered about the performance aspects because I can always refactor for speed later.
Andrew Ingram
I avoid using reflection for major parts of design, but an outright ban is silly.
moffdub
No, it was not allowed, as he didnt understand it. Every piece of code had to be written at his 'level'.
leppie
I guess you weren't allowed to code in .Net at all then. After all, a lot of how the framework executes is through reflection.
Chris Lively
Magic/More Magic
Step 3, PROFIT! :)
leppie
I had a manager once who didn't believe in source code control. We were only allowed to use the VCS (Rational Rose, unfortunately) with checkin and checkout scripts to keep it at a distance, and he would put stuff directly into production without backups. I've seldom been as happy to leave a place.
David Thornley
Down with those **wizards**!! Always around, with their *magic*, stealing our jobs, seducing our women and corrupting our childrens!
ZJR
Of course it's magic – there's a cloud of mysterious smoke and everything just works ...
Marius Schulz
+10  A: 

The strangest one i saw was database table naming where the tables were prefaced with a TLA for functional area, eg accounting ACC then a 3 digit number to (overide the default sort) and then the table name.

Plus this was extended into the column names as well.

ACC100_AccountCode

it was a nightmare to read a query, they were so unreadable.

Adrian
I've seen this too. To make it worse, people started to refer to the tables with the shorthand of their number.. "that's in 452"
WW
Schemas fixed all that crap.
Chris Lively
+112  A: 

Back in the 80's/90's, I worked for an aircraft simulator company that used FORTRAN. Our FORTRAN compiler had a limit of 8 characters for variable names. The company's coding standards reserved the first three of them for Hungarian-notation style info. So we had to try and create meaningful variable names with just 5 characters!

David Arno
ouch, that hurt!
steffenj
Luxury: we had just 6 characters; the package had names starting with g; the internal functions all started gk; there were workstation drivers with codes such as 0p (so gk0p was the start), leaving us two characters for the rest of the Fortran name. gk0paa, gk0pab, ...
Jonathan Leffler
Oh - fortunately we did have a get out; some of the code was written in C and that which did not have to be called from Fortran could use longer names (at least 8 characters -- I forget the exact number now).
Jonathan Leffler
"When I was your age, we only had 2 characters! And it was case-insensitive!"
pookleblinky
We used to have to get up at 2 in the morning, 3 hours before going to bed, then write our own compilers and pay the company for the privilege of going to work. We were allowed just the letter A for our variable names. Then our boss would delete our code and dance on our listings singing hallelujah.
David Arno
Yeah, I know Monty Python too... The 'me too, only better/worse' story is, in fact, true. The package was for the GKS (Graphical Kernel System), hence the initial 'g'. It teaches a name-space discpline, though.
Jonathan Leffler
"50 possible identifiers ought to be enough for anyone" :p
Christian Vest Hansen
Pookleblinky--there really were systems with those rules. The second computer I ever worked with.
Loren Pechtel
If you think that's hard, look at this: http://stackoverflow.com/questions/218123/what-was-the-strangest-coding-standard-rule-that-you-were-forced-to-follow?answer=221510#221510
DR
That's not so bad!I used to code in RPG/400, where variables had only 6 positions, and the first 2 were reserved as a table prefix. So only 4 chars left for meaninful stuff ;-)
Daniel Magliola
That sucks, but at least there was a reason for it.
John MacIntyre
not only that, we had to make it compatible to a wide range of compiers from the ancient FORTRAN-S to vsFort-77 (with 66 compatibility)
Dave
Heck, the BASIC interpreters we worked with a long time ago had two-character variable names. Why complain about 5?
David Thornley
I did work with a BASIC variant that only allowed one character for variable names. Even to a real greenhorn (like I was then) it was obvious that that was a toy system and not something to take seriously.
Donal Fellows
@Donal, reminds me of 'programming' on my TI-83 calculator (in simplified Basic). I was 15, a complete noob, and even back then I kind of had this feeling there was something not entirely right with 1-char variables.
Litso
+9  A: 

It was a coding standard I did not follow myself ( got in trouble for other things, but never that ). We had three 19" monitors, so we could have two editors open to full screen and still have access to the desktop. Everyone else did not use comments, but used meaningful names. Extremely long meaningful names. The longest I remember was in the 80 character range. The average was around 40~50.

Guess what, they didn't accurately describe the whole thing.

BubbaT
for(int ThisIsAnIterativeVariableWhichWeWillIncreaseBy1EachTime = 0; ThisIsAnIterativeVariableWhichWeWillIncreaseBy1EachTime < 10; ThisIsAnIterativeVariableWhichWeWillIncreaseBy1EachTime++) ;
Brian R. Bondy
ITYM:for(int ThisIsAnIterativeVariableWhichWeWillIncreaseBy1EachTime = 0; ThisIsAnIterativeVariableWhichWeWillIncreaseBy1EachTime < 10; ThisIsAnIterativeVariableWhichWeWillIncreaseBy1EachTime+=2);
soru
+11  A: 

You must use only five letter table names and the last two character is reserved for IO.

Zsolt Botykai
Those bytes matter!
TheLQ
+83  A: 

Once worked on a project where underscores were banned. And I mean totally banned. So in a c# winforms app, whenever we added a new event handler (e.g. for a button) we'd have to rename the default method name from buttonName_Click() to something else, just to satisfy the ego of the guy that wrote the coding standards. To this day I don't know what he had against the humble underscore

ZombieSheep
I'm wondering if you worked with me a couple years ago at a 9-month contract. We had the same BS. I understand following the framework guidelines (no underscores) in general, but since VS generates handlers with that syntax (whether via designer or +=) ... Well ...
John Rudy
Ah, I took a quick gander at your profile and realized that you did not. Interesting that you dealt with an egotistical coding standard loony who had some of the same quirks as one I dealt with!
John Rudy
Maybe _ was broken on his keyboard ;)
Roman Plášil
buttonNameUnderscoreClick()
vitule
Well->maybe_he_was(tired_of, exceptionally_long_underscore_names, and_so_banned, them_from_use);
Robert P
Has the unfortunate side-effect of preventing the use of __FILE__ and __LINE__ for debugging. And #if __cplusplus extern "C" in header files. And the integral types in stdint.h. And size_t.
Steve Jessop
And pretty much all of the C++ standard library.
yuriks
Good thing this was C# then
configurator
I seriously discourage underscores (although not in the OP case listed above. It's an extra two keystrokes (shift + _) that I prefer not to have put upon me when pascal or camel case will do just fine.
TGnat
underscores are seriously useful way of having a style in C that can be followed. When we have an existing C library file written with functions_like_this, I hate it when someone adds justOneFunctionLikeThis to the library_with_all_underscores. Some people. How about, try to fit in, more than to impose yourself on others?
Warren P
There was an April Fools gag at a company I used to work it. Someone sent out a fake memo saying that the letter *o* was to be banned in C code (backed up by examples of bad keywords/functions that contained it such as `goto`, `continue` and `longjmp`.)
finnw
+3  A: 

The strangest was that type qualified variable naming must be used in Java, and the types where those of the columns from the database. So a java.sql.ResultSet had to be called tblClient etc.

Martin Spamer
+206  A: 

No ternary operator allowed where I currently work:

int value = (a < b) ? a : b;

... because not everyone "gets it". If you told me, "Don't use it because we've had to rewrite them when the structures get too complicated" (nested ternary operators, anyone?), then I'd understand. But when you tell me that some developers don't understand them... um... Sure.

Jarrett Meyer
By everyone, your boss means himself.
Brian R. Bondy
I actually had a a coworker that was really opposed to the ternary operator because "it hides expensive comparisons". When comparisons are a bottleneck, start thinking about changing your approach to the problem...
korona
I used to fall into this camp ... But grew out of it, and have learned to love the conditional operator (when it's appropriate).
John Rudy
Note that some compilers are brooooken when dealing with ?: on C++ objects... Sun's Studio 8 compiler certainly had a couple of different problems with ?: in that scenario, where things could get destroyed twice or constructed wrong. So if you're going to use ?: on objects, test it!
Mike G.
If anything, the rule should be "always use the ternary operator", an operator of pure beauty :)
Bobby Jack
This is exactly what I was going to say--had it happen to me at my first C job. On the other hand, if you are using it in a situation where someone might have to take an extra 5 seconds to read it over an if statement, skip it. Readability is all that matters.
Bill K
I used to hate the ternary but now i love it, but still use it sparsely. But it's just too great for debugging code because you can put something like this in the assert or log parameters without bloating the code: Log("{0}", (obj != null) ? obj.ToString() : "<null>");
steffenj
I love it, but the reason I get most often for not using is is the same as your experience "people wont understand it". My argument is that they shouldn't be working if they can't understand the concept...
Aidos
@Aidos, I couldn't agree more.
Jarrett Meyer
I'd be afraid to work in such a small-minded environment. Best of luck!
schonarth
I have actually experienced being forced to use it because some code generator only allowed expressions in its inputs, and `if` is a statement.
Christian Vest Hansen
Tell your boss to look at the source of Scheme48.
How else would you conditionally initialize a constant variable without writing a whole new function (which won't do much good for readability). The use of const for local "variables" does much more good for understanding and following the code than a ban of the ternary operator.
Andreas Magnusson
Personally I hate it as well, since its less readable than a plain old if statement.And Andreas, writing a whole new function is just fine if you name it right.
Pyrolistical
Personally, I can't stand reading code that uses the ternary operator. It just kills the readability for me.
Peter Bernier
@Aidos, I was going to say the same thing.
John MacIntyre
I dont mind it as long as its kept simple. The job-security kind of guys or the guys who love to write fancy unreadable code who make a ternary that looks like a single line of 256 bit crypto.. should not be allowed to use them.
Neil N
+11  A: 

Applying s_ to variables and methods which were deemed "safety critical" for software that was part of a control system. Couple this with the other rule about putting m_ on the front of member variables and you'd get something ridiculous like "s_m_blah()", which is darn annoying to write and not very readable in my opinion. In the end some 'safety expert' was supposed to gain insight by looking at the code and determining something from it by using those "s_" - in practice, they didn't know c++ too well so they couldn't do much other than make reports on the number of identifiers that we'd marked as 'safety critical'. Utter nonsense...

itsmatt
MS does this in vc++ with a suffix _s.
Brian R. Bondy
Mark Baker
Does the `s_` always come before the `m_`?
Brad Gilbert
Was the objective to write perverted code? <G>
Loren Pechtel
@Brian: I thought that was because they added those `_s` functions later... had the functions been safe in the first place, they wouldn't have needed a variant.
Mark
+2  A: 

We have a no code past the 80th character column that is controversial in our C++ development team. Liked and code review enforced by some; Despised by others.

Also, we have a very controversial C++ throw(), throw(...) specification standard. Religiously used by some and demonized by others. Both camps cite discussions and experts to enforce their respective positions.

tfehrs
We don't religiously enforce the 80 character limit, but it's a good guideline and most of us like it. It's not in our (barely existant) coding standards, just something we have agreed on. If you ever end up looking at code in a terminal window it's nice not to have to resize it.
Mark Baker
When's the last time you looked at code in a terminal window? I just expand my terminal if I have to, or use the -S flag to less, or just open the code in my favourite syntax-hilighting editor. Sheesh.
Tanktalus
Quite often actually, and yes of course I can expand my terminal if I have to, or any of the other options, but I'd rather not have to.
Mark Baker
Also, if you stick to 80 columns you can easily have two windows side-by-side on screen. You don't have to stick religiously to 80 columns for that to be true, but anything over about 100 columns and you can't, with sensible sized fonts on a 1600x1200 screen.
Mark Baker
+1 for two windows side by side :) I tend to have two consoles stacked on the left and my editor to the right.
Christian Vest Hansen
an 80 char limit is sensible, but there are times when it should be broken. Not very many, though.
Wayne Werner
+28  A: 

Doing all database queries via stored procedures in Sql Server 2000. From complex multi-table queries to simple ones like:

select id, name from people

The arguments in favor of procedures were:

  • Performance
  • Security
  • Maintainability

I know that the procedure topic is quite controversial, so feel free to score my answer negatively ;)

azkotoki
Performance is improved because SQL Server can more quickly identify the cached compiled form of the query. Security is improved because static compiled SQL stored procedures are not vulnerable to injection attacks. (continued)
Jeffrey L Whitledge
Maintainability could be improved if the table and column names are not unique, but the SP names are. This could make code references easier to find. If there are any other, better maintainability advantages, I am not aware of them. Security is the main reason to use SPs.
Jeffrey L Whitledge
I agree that for general purposes it's not 100% wtf, but see this link: http://www.codinghorror.com/blog/archives/000292.html
azkotoki
In SQL2000, locking is an issue for some forms of DB architecture. It can kill performance totally. Putting your queries in SPs gets around that a lot as they're faster (and get less lock contention) and the DB can optimise some away, IIRC.
gbjbaanb
It also provides very good abstraction from your database, this is a good thing, you should embrace it instead of trying to be a lazy programmer :-)
gbjbaanb
This rule is probably a good idea if the database is maintained by an external team. If you are in control of the database, though, then it is a dumb idea.
Trumpi
gbjbaanb, can you site your source? I'm interested in knowing more about this fact.
cciotti
"Security is the main reason to use SPs" No. Nothing about SP's in SQL Server are more secure. They are only secure when called as a paremeterized queries, which can be done just as well with dynamic SQL.
Flory
Performance: You should know that queries in SPs are not compiled, their execution plan is cached (this happens also in dynamic SQL). Maintainability: Database is for storing data. Keeping application behavior there doesn't sound "organized" to me
azkotoki
stored procedures need to die
Shawn Simon
Nah: sprocs are useful. While it can be a pain at times, you end up writing a better, more reusable database interface. Your dba's can also have an easier time analyzing performance problems and can update a production system without an app code change. I don't advocate biz logic in sprocs though.
Robert Paulson
burying queries in compiled code is such a pain, I'm 100% behind 100% sprocs policy for the abstraction alone
annakata
The big performance gain in sprocs comes when you have a variety of operations to perform to support a single business process. If you are going to perform 5-10 database operations within a transaction, all rooted in a few args, then a sproc saves the time needed to submit 5-10 calls.
Mark Brittingham
You're right Mark, it's a good place to use them. With my post I meant that the real problem is when people abuses sprocs, using them for *every* database call.
azkotoki
Performance could be much worse as only single execution plan can be cached and that plan may be no good for for certain parameters passed to the procedure. SQL Server caches execution plans for adhoc queries anyway -- they don't even need to be prepared!Security is the same -- you must always escape any ad-hoc data sent to the server. Failure to do so will not prevent bad things from occuring.On maintainability they got you there :) I've lost track of the number of times I was able to "patch" a running system with no compiled code changes simply by updating procs.
Einstein
+10  A: 

If I remember correctly the delphi IDE did a default indent of two spaces. Most of the legacy code for the company had three spaces and was written by the VP IT and the CEO. One day, all the programmers were talking about what we should do to make our lives easier and a contractor who knew Delphi pretty well said, "Hey the ide defaults to two spaces does anyone have a problem with us doing this going forward for new code?" All of us looked at each other, and pretty much thought it was a no brainer and said that we agreed.

Two days later the VP and CEO found out we were going to make such a dangerous change that could "cause problems" and instructed us that we would be using three indents for everything until the two of them could accurately evaluate the impact of such a change. Now I am all for following standards, but these are the same people who thought oo programming was creating an object with one function that had all of the logic necessary to perform an action, and that source control was moving the code files to a different directory.

Kevin
You can set the indent in the environment options!
Loren Pechtel
Ah HA!! So THATs where three spaces comes from!
Robert P
I will never understand why people hate with a passion a simple space or tab.
TheLQ
+1 because I just left a job where I started under one of these programmers, management couldn't understand why working with legacy code was so time consuming: "people who thought oo programming was creating an object with one function that had all of the logic necessary to perform an action, and that source control was moving the code files to a different directory"
qstarin
+96  A: 

I worked at a place that had a merger between 2 companies. The 'dominant' one had a major server written in K&R C (i.e. pre-ANSI). They forced the Java teams (from both offices -- probably 20 devs total) to use this format, which gleefully ignored the 2 pillars of the "brace debate" and goes straight to crazy:

if ( x == y ) 
    {
    System.out.println("this is painful");
    x = 0;
    y++;
    }
Michael Easter
yuckers. This is patently the worst bracketing style ever.
nickf
wtf! That's horrible!
Gary Willoughby
ps. The silly 'reason' was so that it would be easier for people to transfer context from C to Java and vice-versa.
Michael Easter
I would think that maintaining a greater visual distinction between C and Java would make the transitions easier. (+1 for "and goes straight to crazy.")
Jeffrey L Whitledge
That is horrendous...
chills42
Looks like Whitesmiths style which was used in the original 'Programming Windows' by Petzold - go figure! ;)
Bobby Jack
This seems to be the style favoured by brian d foy, who's a member of stackoverflow: http://search.cpan.org/src/BDFOY/Business-ISBN-2.03_01/lib/ISBN.pm
I remember seeing that when I was first starting in C. Always disturbed me a bit--I guess because the braces are part of the if statement, not the looping code,
Bill K
its pretty much using python style - only python dumped the braces as they're redundant in this style.
gbjbaanb
I always use the Perl style formatting, because it makes it easier to tell when you're just in a block for scoping reasons.
Brad Gilbert
Good that they at least allowed declaring scope variables not only at the beginning of the block. ;)
macbirdie
I've seen this style from people whose first programming language used 'begin' and 'end' keywords. I theorize that they are mentally translating "{" to "begin" and "}" to "end". I don't know; there may be other reasons, too.
Alan Hensel
I find this the most intelligent brace style. Unfortunately, most people don't use it. If braces have semantic meaning, they should be treated like it, not stuck at the end of a line and ignored.
Kyralessa
@Kyralessa. I disagree... I don't know if braces have semantic meaning but they can certainly affect pattern-matching and a sense of space. IMO, this version loses that completely. e.g. I want my bookmark to poke outside the book, not be flush with the pages.
Michael Easter
I have seen this style before. The idea is that indentation shows nesting. Many people prefer this over having the { and } on the same level as the previous statement and just the sub statements indented. I prefer { on the line above and } on the same indentation as the statement causing the {}
Cervo
This is actually my preferred style, but everything in the world (Visual Studio especially) defaults to other modes, so I've given up.*Why* do I like it? The braces *are* "part of" the contained code -- they force it to "look like" a single statement to the if, which is what it expects.
Atario
My workplace does this (and for Java). It made me twitch for a couple of weeks, but I got used to it pretty quickly and I like it now. It's better than "OTBS", at least (I was an ANSI/Allman guy before).
Adam Jaskiewicz
This was also my preferred style, but this whole comment thread is the best reason why I like Python now - no bickering over where the braces go!
Paul McGuire
@Michael: Braces do have semantic meaning in C and many other languages derived from it (they denote the scope of variable contexts).
Donal Fellows
+6  A: 

I worked in a place where the coding standard was one giant WTF: strange Hungarian notation, prefixing globals with 'g' and members with 'm' (so there were gems like gsSomeVariable), adding 'ref string sError' to every single function, instead of throwing exceptions (which was a BIG nono!).

The killer, though, was prefixing the function parameters with I_ for input parameters, and O_ for output parameters.

I work now in a much better place :)

hmemcpy
adding 'ref string sError' to every single function, that best practice they show in computer science 101 at my university!
pmlarocque
Prefixing globals with 'g' is simpler than putting a "here be dragons" comment on every fucntion.
Martin Beckett
don't know your platform, but this kind of stuff is typical VB6. Probably, if you're not in VB6, the person who made the rules comes from that background and wanted it to conform to what he's used to. It was wrong in vb6 too, but you know...
Troy Howard
I really like the g, and m prefixes... I and O seem a bit weird...
Brian Postow
g_ for globals, p_ for parameters, l_ for local variables, cp_ for cursor paramaters ... I used that in PL/SQL programming. I don't think that's bad.
tuinstoel
A Porcupine Tree Fan!
Mark Brittingham
Porcupine Tree are awesome! :)
hmemcpy
Who me? I can tolerate the porcupine trees but to say that I like them... no, not really. Or do you mean someone else?
tuinstoel
I think he meant me, since I have an icon of their album In Absentia, which is in my mind nothing short of a masterpiece.
hmemcpy
What's with the phrase 'here be dragons'? I've seen that at multiple companies - where is it from?
JBRWilkinson
@JBRWilkinson http://en.wikipedia.org/wiki/Here_be_dragons
hmemcpy
I argue that g and m are good prefix because: Globals::variableName is annoying to type (and NEVER EVER use the C++ global scope) and this->variableName is also worse to type (compare this->okButton with mOkButton in a member function. Which is easier to type?)
iconiK
+24  A: 

There must be 165 unit tests (not necessarily automated) per 1000 lines of code. That works out at one test for roughly every 8 lines.

Needless to say, some of the lines of code are quite long, and functions return this pointers to allow chaining.

harriyott
How is a unit test not automated.
J. Pablo Fernández
How did they come up with the magic number 8?
Rohit
I think that by "not automated" he means "not repeatable".
Trumpi
One test per 8 lines is actually not very many at all... Do you mean you can have AT MOST 165 tests?
Orion Edwards
What happens if you have 164? 166?
Daniel Daranas
More like 6 lines.
recursive
@Orion that depends heavily on the language.
Wallacoloo
It depends on how finely grained your tests are too I guess. I'd consider `function(x).should == 2` to be a single test, whereas others would bundle 10 of those together and call it a single test.
Orion Edwards
+73  A: 

A buddy of mine encountered this rule while working at a government job. The use of ++ (pre or post) was completely banned. The reason: Different compilers might interpret it differently.

JaredPar
Well, at that point you might as well give up, right?
Just Some Guy
Some one got bitten by not understanding the difference between postfix and prefix, claimed compiler bug, then inflicted it on other people, me thinks.
Bernard
Oddly, in C/C++ that did hold true, an instructor gave us an example from back in the day. Although, not sure if it still applies.
MagicKat
Actually, they were right, in some circumstances. Banning seems a bit over the top though. Take for example, the line : a[i] = i++;i may get incremented before it is used to index a, or after. The language does not define this.
T.E.D.
He's right--the order of operations is not guaranteed when you use the same variable elsewhere in the statement. Just ban potentially ambiguous code, not all uses of it, though!
Loren Pechtel
@ted.dennison - Actually, the language specifically defines that line as illegal. (you may only use a variable once in a line, if you modify it)
James Curran
Why is this such a problem? You can still do i = i + 1 or i += 1?
tuinstoel
@tuinstoel: Not in modern C++, you don't. You don't normally increment or decrement an iterator by adding or subtracting 1. @MagicKat: What probably happened was a line that modified a variable twice without an intervening sequence point, like `i = i++;`, which is undefined behavior. Banning undefined behavior is a good idea; banning all language constructs that can cause undefined behavior isn't.
David Thornley
Hotei
Might as well ban `=` as it can be used to cause undefined behaviour.
configurator
+1  A: 

All file names must be in lower case...

jmcd
That's not unreasonable if the code is supposed to be cross-platform and any of the targets is case-sensitive. It's easier to pick a case and stick with it, and at least THEY DIDN'T PICK ALL CAPS.
Just Some Guy
I agree with Just Some Guy. And here's another such standard I like: NO spaces in file or directory names! (If you must, substitute the underscore or period...)
Richard T
It *is* unreasonable if you are coding Java and the filename has to match the class name.
Dan Dyer
OK, that's a pretty reasonable case for overriding the rule.
Just Some Guy
+4  A: 

We have to put a comment above every sql statement. So, you may have an sql statement as such

Select USER_ID FROM USERS WHERE NAME = :NAME;

And you still have to have a comment above it that would say:

Select USER_ID from the USERS table, where name equals the name entered.

Now, when the actual comment is longer than the code, and the code is simple enough for a second grader to read, i really don't see the point of commenting... But, alas, I have had to go back and add comments to statements just like this.

This has been on a mainframe, coding in cobol. Team size is usually about 4 or 5, but this rule has bitten everyone here from time to time.

CobolGuy
Well... It's the COBOL that's your problem! The designers of COBOL had a mindset that EVERYTHING had to be spelled out in what one may call "longest notation possible." ...I LITERALLY "threw the book away" when I read that to express subtraction I had to type the word SUBTRACT, and couldn't use -.
Richard T
C'mon. You can use -. You have to do it in a COMPUTE statement, something like COMPUTE NET_PAY = HOURS_WORKED * RATE. Hey, what can you expect from a language where ZERO, ZEROS, and ZEROES are all reserved words, and mean exactly the same thing?
David Thornley
+21  A: 

My weirdest one was at a contract a couple years ago. @ZombieSheep's weird one was part of it, but not the weirdest one in that company.

No, the weirdest one in that company was the database naming scheme. Every table was named in all caps, with underscores between the words. Every table had a prefix (generally 1 - 6 characters) which was usually an acronym or an abbreviation of the main table name. Every field of the table was prefixed with the same prefix as well. So, let's say you have a simple schema where people can own cats or dogs. It'd look like this:

PER_PERSON
    PER_ID
    PER_NameFirst
    PER_NameLast
    ...
CAT_CAT
    CAT_ID
    CAT_Name
    CAT_Breed
    ...
DOG_DOG
    DOG_ID
    DOG_Name
    DOG_Breed
    ...
PERCD_PERSON_CAT_DOG (for the join data)
    PERCD_ID
    PERCD_PER_ID
    PERCD_CAT_ID
    PERCD_DOG_ID

That said, as weird as this felt initially ... It grew on me. The reasons behind it made sense (after you wrapped your brain around it), as the prefixes were there to be reminders of "recommended" (and enforced!) table aliases when building joins. The prefixing made the majority of join queries easier to write, as it was very rare that you'd have to explicitly reference a table before the field.

Heck, after a while, all of us on the team (6 people on our project) were able to begin referring to tables in conversation by nothing more than the prefix. An acquired taste, to be sure ... But one that grew on me. So much so that I still use it, when I have that freedom.

John Rudy
Interesting... It'd take a while to get used to, but I think I'd actually like that one too.
chills42
My experience is Oracle people like to do things like this.
Craig
That probably was the case -- it was a SQL Server environment, but I'm pretty sure most of the standard-setting DBAs had heavy Oracle backgrounds. In any event, we can now count another dyed-in-the-wool SQL Server guy as liking it ... Like I said, it grew on me. :)
John Rudy
Hmmm I work with SQL Server and I think this is a good idea as well...
Cervo
I can think of no better way of allowing people to discover who they would respectively dread either working for, or having work for them. You guys are on my list, feel free to put me on yours. :)
ChrisA
Interesting. I'm not sure whether I'd hate it or love it after a while. My initial reaction is, "ugh", though.
Paul Nathan
We use that at work, and i like it too :) The only difference for use is that the prefix is not on table names and is always 3 characters
Pondidum
I just barfed in my mouth a little.
Emtucifor
And there was me thinking that `<tablename>.` was a good enough prefix for putting on column names. That's told me.
Christian Hayter
This totally reminds me of the DBAs at an insurance company in Ottawa Ontario Canada that I used to work with.
Warren P
+7  A: 

The one that got me was similar to the other poster's "tbl" prefix for SQL table names.

In this case, the prefix for all stored procedures was to be "sp_" despite the fact that "sp_" is a prefix used by Microsoft for system-level stored procedures in SQL Server. Well, they had their standards from an old, non-MS database and weren't about to change just because their standard might cause a stored procedure to collide with a system stored procedure and produce unpredictable results. No, that just wouldn't be proper.

David
Naming stored procedures with sp_ is also a performance hit -- MS SQL assumes that they're in the master DB, and when it can't find them, it regenerates the execution plan...
Roger Lipscombe
@Roger -- thanks for the info. I've inherited my fair share of these (my own standard usp_) from other developers; good to know about the performance hit.
John Rudy
It is very common in my experience to prefix stored procs with sp_ in SQL Server. I have seen it in many places. I prefix procs with proc_ and functions with fn_.
Craig
sp was the prefix used by Sybase - long before MS SQL Server came into being (by adapting Sybase).
Jonathan Leffler
doesn't it help when you see something like "SELECT * FROM vwPatients" to know you are referencing a view insteal of a table...that would be "SELECT * FROM tblPatients"
MBoy
@MBoy: Now when you don't have views...
configurator
+10  A: 

What drives me nuts is people suffixing the ID field of a table with the name of the table. What the hell is wrong with just ID? You're going to have to alias it anyway... for the love of all that is sacred!

Imagine what your SQL statements look like when you've got id fields called IDSEWEBLASTCUSTOMERACTION and IDSEEVENTLOGGER.

Rob Stevenson-Leggett
Actually I think it makes queries easier to write and read. I do this.SELECT * FROM Person P LEFT JOIN PhoneNumber PN ON P.PersonID = PN.PersonID
Craig
Gotta agree...the suffixing makes database design easier...specially on tables with a lot of foreign keys.
MBoy
my preference: ... from customer left join address on (address.id = customer.address_id)
Christian Vest Hansen
Why do you have alias it anyway? Don't understand.
tuinstoel
The OP is talking about putting the table name *after* 'ID', which is just weird.
JBRWilkinson
Putting it before is debatable, in certain situations it makes stuff cleaner. However, putting after is just dumb
TheLQ
+203  A: 

To NEVER remove any code when making changes. We were told to comment all changes. Bear in mind we use source control. This policy didn't last long because developers were in an uproar about it and how it would make the code unreadable.

George
I really hate that... there's a few people who do that here (it's not a standard or anything though)
chills42
Rules like that are why I feel a NEED to print source code I inherit from others in color. At a dime a page, that's not very nice to my company -- but it's the only way I can read it if I have to print it. (We've inherited a lot which followed this rule ... )
John Rudy
Sounds like a rule developed pre source control. Or due to programmers only checking in once a week.
Craig
Craig, you're absolutely right on that. How about checking in once a release!
George
aaaargh! place I worked still had that as standard as they didn't have source control :-(
interstar
That's just insane.
Chris Needham
I've done this on maintainence projects without source control, then remove all the comments after it passed validation testing. But now, I'd have to be in a real bind before I'd work without source control! This isn't 1995 anymore!
John MacIntyre
Some places WORK without source control?
Mark Schultheiss
I love reading these answers because it makes my job seem 100x better.
rjh
Feel for you... we're on SVN for 4+ years, but the senior developer hates it and checks in about once per two months, spending the next three days complanining about broken code :/
Viktor Svub
+39  A: 

I've had a lot of stupid rules, but not a lot that I considered downright strange.

The sillyiest was on a NASA job I worked back in the early 90's. This was a huge job, with well over 100 developers on it. The experienced developers who wrote the coding standards decided that every source file should begin with a four letter acronym, and the first letter had to stand for the group that was responsible for the file. This was probably a great idea for the old FORTRAN 77 projects they were used to.

However, this was an Ada project, with a nice hierarchal library structure, so it made no sense at all. Every directory was full of files starting with the same letter, followed by 3 more nonsense leters, an underscore, and then part of the file name that mattered. All the Ada packages had to start with this same five-character wart. Ada "use" clauses were not allowed either (arguably a good thing under normal circumstances), so that meant any reference to any identifier that wasn't local to that source file also had to include this useless wart. There probably should have been an insurrection over this, but the entire project was staffed by junior programmers and fresh from college new hires (myself being the latter).

A typical assignment statement (already verbose in Ada) would end up looking something like this:

NABC_The_Package_Name.X := NABC_The_Package_Name.X + 
  CXYZ_Some_Other_Package_Name.Delta_X;

Fortunately they were at least enlightened enough to allow us more than 80 columns! Still, the facility wart was hated enough that it became boilerplate code at the top of everyone's source files to use Ada "renames" to get rid of the wart. There'd be one rename for each imported ("withed") package. Like this:

package Package_Name renames NABC_Package_Name;
package Some_Other_Package_Name renames CXYZ_Some_Other_Package_Name;
--// Repeated in this vein for an average of 10 lines or so

What the more creative among us took to doing was trying to use the wart to make an acutally sensible (or silly) package name. (I know what you are thinking, but explitives were not allowed and shame on you! That's disgusting). For example, I was in the Common code group, and I needed to make a package to interface with the Workstation group. After a brainstorming session with the Workstation guy, we decided to name our packages so that someone needing both would have to write:

with CANT_Interface_Package;
with WONT_Interface_Package;
T.E.D.
With all that and NASA still couldn't figure out whether to calculate in kilometers or miles...
Chris Lively
Damn, and I really thought you were going to go all out and use a CUN*_ and W*NK_ package naming convention. Sorry, I have slow-burning, explosive, textual tourettes.But yours were much, much, funnier!
defmeta
+72  A: 

At a former job:

  • "Normal" tables begin with T_
  • "System" tables (usually lookups) begin with TS_ (except when they don't because somebody didn't feel like it that day)
  • Cross-reference tables begin with TSX_
  • All field names begin with F_

Yes, that's right. All of the fields, in every single table. So that we can tell it's a field.

Jeromy Irvine
and you had no special prefix for primary key fields???
Czimi
@Czimi: I forgot to mention that. Every table has a field called FI_ID used as the primary key.
Jeromy Irvine
Holy sh... The T_guy who invented this nightmare should be killed with a F_gun and sent to TSX_hell.
Sergey Skoblikov
We had tbl and fld for all fields and tables. Completely useless...
configurator
If your database also has 'view's, at least you know if you are accessing a table or a view
jab
@jab: Fine, but why wouldn't you just prefix the views then? Surely you have more tables than views.
ryeguy
Ahh... redundancy.
TheLQ
@configurator: You had “tbl” for all fields and “fld” for all tables? :-)))
Timwi
+20  A: 

Several WTF's in one VB6 shop (I'm not proud, I was hungry and needed to eat) back in 2002 - 2004.

The most annoying IMHO, was setting all object references to nothing at the end of the sub/function. This was to "help" the compiler reference count. It didn't matter how many tests I performed for the TA to prove it wasn't necessary, Oh no, it still had to be done, even though he had absoutely no evidence to back him up what so ever. Eventually I gave up and about a year later found an article explaining why it was pants. I bring this to the TA thinking "Got the fecker!". He goes "Yeah, I've known about that for years, but if you start changing the standard the sheep " meaning other developers, the people he worked with everyday "will screw it up". Gob sh1te.

Others in the same shop.

  • Never delete code, always comment it out (even though we were using source control).
  • Prefixes on table names that were meaningless when I got there, but had to be enforced on new tables.
  • Prefixing all objects with o_ (lo_ for procedure level references, mo_ for module, go_ for global). Absoutely pointless in a project where every other variable was an object reference.

Mostly I was writing c++ there (only c++ developer, so made own standards, and enforced with rigor!) with occasional vb, otherwise I wouldn't have lasted.

Binary Worrier
Sadly, at my last job we were working with Java, and haing OutOfMemory issues and seemed to have a memory leak. The consulting company we were working with actually proposed and implemented, setting every variablse back to null at the end of methods. Needless to say, the problems didn't go away :)
rally25rs
TA = Technical Architect, or Technical Guru, a role often appointed, rarely earned. The guy at my current job is EXCELLENT, he raises the bar for everyone.
Binary Worrier
"Never delete code." I just imagine my starting days, when there was no syntax coloring by default. Then this would count as torture.
DerMike
+2  A: 

The creator of the file (doesn't have to put any code in) has to put their name in the file. So if you create stubs or placeholders, you "own" them forever.

The guy who actually writes the code doesn't add his name; we had source control so that we'd know, always who to blame.

Sam Hoice
Huh... not really sure how that'd ever be useful...
chills42
Did that have anything to do with holdovers from COBOL and the AUTHOR. clause in the IDENTIFICATION DIVISION.?
David Thornley
It's possible, although since the company was primary made hardware, I'd think Fortran was a more likely ancestor.
Sam Hoice
+4  A: 

I completly disagree with this one, but I was forced to follow it:

"All HTML LINKS will ALWAYS be underlined."

A while back I explained why I disagree on my blog.

Note: Even Stackoverflow ONLY underlines links when you move the mouse over them.

Bobby Ortiz
Is there a reason you use "consistence" instead of "consistency?"
Kevin
But this is the default in most browsers, so it's not likely to confuse anyone.
finnw
+7  A: 

no single character variable names - even for a simple iterator like i. Had to use ii or something. I thought this was stupid.

Another one - perhaps the craziest of all, but maybe not a coding standard...

no STL allowed. and this was in 2007/2008. I left there soon after I found out about that nonsense. Apparently some idiots thought that there was no "standard" (As in 15 years ago...) I guess they missed the memo about stl being in the C++ standard...

Use of the stupid COM HRESULTs as return types for just about ALL methods - even if they are not COM. It was ludicrous. So now instead of returning some enumerated type or a useful value that indicates a result, etc, we had to look up what S_OK or E_FAIL or whatever meant in the context of each of the methods. Again, I left there shortly after that.

Tim
sounds like someone was missing an algebraic Maybe type.
Christian Vest Hansen
This HRESULT thing can be sort of OK. If you don't want to use exceptions, you should return a condition, and test it. An HRESULT is as good as any. Using it as the return value allows you to do this:HRESULT res;if ( FAILED(res= dothis(...)) || FAILED(res= dothat(...))) HandleError(res);
TonJ
The purpose of ii instead of i is that it's easier to search for. But if you have an IDE that can do "Find Whole Word", it's not really a big deal.
Kyralessa
if the scope of an iterator variable is that long/large then there is something wrong with the coding. Arbitrary rules to try to make searching for variable names easier is a bad idea. Additionally, with the IDEs these days, who needs to do a search?
Tim
HRESULTS are useless unless you are using COM. It is not a good idea to force that paradigm on better practices. UGH!
Tim
I'm not too happy with i and never use it. Sometimes x, y and perhaps even z make excellent sense, though.
Loren Pechtel
Using repeated characters for small variables (ii for example) does make them easier to search for. Searching for references to i will get anything that has i in it whereas searching for ii will get much fewer false positives. It's actually quite a good practice.
ConcernedOfTunbridgeWells
@ConcernedOfTunbridgeWells Why in the world would you EVER need to search the code for an iterator variable? Good practice? Not likely.
Tim
+17  A: 

Every beginning and ending brace was required to have a comment:

public void HelloWorld(string name)
{

  if(name == "Joe")
  {
    Console.WriteLine("Hey, Joe!");
  } //if(name == "Joe")
  else
  {
    Console.WriteLine("Hello, " + name);
  } //if(name == "Joe")
} //public void HelloWorld(string name)

That's what led me to write my first Visual Studio plugin to automate that.

Cory Foy
God I hate those types of comments - all they do is add visual litter to the screen
matt b
Generally I agree, @matt ... But when you're handed a 444-line VBScript classic ASP page littered with very long (90+ LOC) nested ifs, it can be tremendously helpful. Assuming, of course, that the original developer matched them correctly. Which, in code like that, may not be a safe assumption!
John Rudy
if you have very long nested if's, then this kind of comments is just a little duct tape instead of a real fix (that is, extracting methods and such)
Tetha
the rule you need in that case should be "no crazy nested ifs"
hasen j
OMG! Don't most IDE text editors do curly-brace highlighting/matching now?
JBRWilkinson
*clicks minimize button in IDE. Oh, thats what it does
TheLQ
So why do none of the beginning braces in your example have comments?
Jesse C. Slicer
These are actually very common in C headers(`#ifndef __HEADER_H__ #define __HEADER_H__ #endif /* __HEADER_H__ */`)
luiscubal
+5  A: 

As I always worked self-employed/freelancer/project leader, I never got into someone's standards, all standards are my decisions. But, I recently found a fun piece of "coding standards document" back when I was 15:

All functions must be named "ProjectName_FunctionName".

Well, procedural PHP, anyone? Those weren't times of hard PHP OOP yet, but still. If I wanted to use code from one project to another, I would have to rewrite all references, etc.

I could have used something like "package_FunctionName".

+73  A: 

Totally useless database naming conventions. Every table name has to start with a number. The numbers show which kind of data is in the table.

  • 0: data that is used everywhere
  • 1: data that is used by a certain module only
  • 2: lookup table
  • 3: calendar, chat and mail
  • 4: logging

This makes it hard to find a table if you only know the first letter of its name. Also - as this is a mssql database - we have to surround tablenames with square brackets everywhere.

-- doesn't work
select * from 0examples;

-- does work
select * from [0examples];
Kristof Neirynck
I am sorry, so terribly sorry...
Just Some Guy
Wow - good one. I guess using Letters was out of the question? Not that THAT is a good idea either but at least you don't have to quote all table names.
Mark Brittingham
mind boggling...who came up with that? the dba?
dotjoe
ewwwwwwwwwwwwww
thomasrutter
incredible:))))
Cristian Boariu
Hmm... I pity you!!!
Microkernel
You're kidding, right?
Marius Schulz
+1  A: 

Back in my COBOL days, we had to use three asterisks for comments (COBOL requires only one asterisk in column 7). We even had a pre-compiler that checked for this, and wouldn't compile your program if you used anything but three asterisks.

Patrick Cuff
+61  A: 

Half of the team favored four-space indentation; the other half favored two-space indentation.

As you can guess, the coding standard mandated three, so as to "offend all equally" (a direct quote).

Tim Lesher
see children, look what happens if you don't play nicely with others :-)
gbjbaanb
Yes, the two spacers should have given in.
wnoise
Thats why tab identation is so great. Everyone can change the size in his editor ;)
xardias
Yeah, tab indentation is great... until you actually open someone else's file, and find things misaligned because spaces got mixed in where they shouldn't have, or didn't get mixed in where they should have. Then you auto-reformat, and version control diffs get ugly. Ugh.
Alan Hensel
I agree with Alan. mixing tabs and spaces makes for code that only looks right on one person's machine. Using three spaces (my preferred method) looks beautiful always. Although my code doesn't.
that's why you're supposed to use only tabs to indent, and only spaces to align, and never the twain shall meet. and if you're going to make a change to the whitespace in a file, then that needs to be the only change you make for that particular check-in.
joh6nn
...and that never works. :P
Robert P
I recommend to people with indenting problems to statistically determine the original authors tab indention and replace it with tabs. Works surprisingly well.
MathGladiator
That's how I came to love AccuRev's option to "Ignore Whitespace" when diffing. Simply awesome.
mxp
I don't see the problem here. There needed to be a standard, and somebody had to mandate something. The phrasing was a little odd, I'll grant you, but the reasoning was OK.
David Thornley
3 seems like a fine decision to me but maybe I'm just one of those wimpy Europeans who likes compromises too much.
tuinstoel
To "offend all equally"... I love it. I'm going to have to remember this the next time I'm somehow invloved in an indentation standardization war.
Michael Burr
Strangely enough Visual Studio has spaces set as default. This has one advantage though: Since I always have visible white-space activated, I can detect changes in my own (tab formatted) code touched by other devs (defaulty space formatted) on first sight :)
Vinz
I use mixed-tab/space in the proper way, and never do the wrong thing, because my editor greenlines if I do (similar to incorrect grammar in Word).
Xiong Chiamiov
Erm... use an decent text editor and change it there? Tabs can be rendered diffrently, and a nice Format tool goes long ways.
TheLQ
For indentation, having a disagreeable coding standard is still better than having no standard at all. Developers will get used to whatever they're told to use.
rjh
@rjh Agreed, but that's a false dichotomy. When half the team preferred A, and half preferred B, I would rather have had one or the other, even if it's not the one I preferred!If I want a blue car (but red would be acceptable) and my wife wants a red car (but blue would be acceptable), buying a purple car is not a good solution.
Tim Lesher
@joh6nn: The problem really comes when you've got trailing-line comments. There is just *no* way to make those align without standardizing tab widths between developers.
Donal Fellows
The best advice I've seen in this area is to separately standardize tab behavior and indentations, and to not conflate the two. (The Tcl coding spec says that tabs are 8 chars and indents are 4, and it says *nothing* about whether you indent with tabs.)
Donal Fellows
+3  A: 

I implemented and modified an open-source asp classic shopping cart (that is mostly a long string of dailyWTF candidates,) that started every variable with a lower case p. As in, pTax_Amount or pFirst_Name.

There was no explanation for this, tho I read somewhere on one of their forums it was to avoid using reserved words like State - you'd have pState instead. They also append temp to things kinda randomly. like rsTemp, and connTemp. As opposed to the permanent record sets and database connections, I guess.

Lance Kidwell
Reserved names maybe, but not for the entire codebase
TheLQ
+7  A: 

I was told that old code should be commented out rather than being removed; in case we needed to refer to the old code (yes, the code was in source control...). This doesn't seem that bad, until major changes are made. Then it becomes a nightmare, with entire sections deleted all over the code.

Giovanni Galbo
i often do that so that no one trys to fix my fix. I have had to leave comments like "please do not change this line, this is really the correct way to do this" when working on a "team" of programmers who would consistently re-introduce bugs that I fixed, because they were sure my fixes were wrong.
Troy Howard
I sometimes to that actually, but I move them to the bottom. Its helpful in between commits.
TheLQ
+285  A: 

reverse indentation. For example:

    for(int i = 0; i < 10; i++)
        {
myFunc();
        }

and:

    if(something)
        {
// do A
        }
    else
        {
// do B
    }
Oh my god ... Can I meet the sociopath who came up with that one? He could teach me a thing or two about misanthropy.
John Rudy
this makes my head hurt
Ólafur Waage
That can't possibly be true.
Dane
I just stabbed my eyes out. Thx for posting.
Jarrett Meyer
I've seen code with indentation similar to this. Thankfully it was not a coding standard or anything like that, just what one dev felt was a good way to indent something.
Doug
I can't believe that this is true.
Marcin
This is too bad to be true. And if true, the guy who invented this revers indentation should be examined by Dr. House in Plainsboro
rshimoda
That indentation makes me a sad panda. :(
Bernard
Every time you reverse the indentation, God kills a maintenance developer.
Christian Vest Hansen
The second one is the Gnu style for C. So no, it is not a joke:http://www.gnu.org/prep/standards/standards.html#Formatting
David Cournapeau
Those standards are nothing like the ones in the OP.
IainMH
This is Stack Overflow, not The Onion!
Loren Pechtel
the guy who invented it started out writing SQL?
interstar
don't believe it, need to see proof
annakata
OMG, are you kidding?
Andrea Ambu
saves precious bytes... priceless, use it a lot
Spikolynn
That made me extremely sasd inside.
Andrew Szeto
I've seen it before, and it makes me want to vomit.
PintSizedCat
dear lord, I'd stab my eyes out.
dotjoe
My first instinct when I saw this was to edit it to correct the indentation... until I realized that the indentation was actually intentional...
Martin B
@David Cournapeau: I didn't find any place in the GNU coding standard you linked to where reverse indentation was advocated -- the example I saw uses normal indentation. You realize that whatever code replaces `// do A` in this example would appear at the zero-th indendation level (i.e. no spaces or tabs to the left of it)?
Martin B
No, the second example is not GNU. What connects it to GNU style though is the weird belief that spaces before opening braces on new-lines are a good thing.
Georg Fritzsche
I use reverse indentation whenever switching between languages. For example javascript or CSS inline with HTML, I reset the indentation on language change. Same for PHP blocks in HTML.
Andrew
I use reverse idention for the #if of a C# Preprocessor Directive.
tuinstoel
Is this a joke?
fastcodejava
wtf lol rofl rofl
Behrooz
You must have made this up!
So say if you add a new if-statement somewhere on the deepest level, you will need to indent the whole code around it? Is this an Arab thing, since they write from left to right? LOL
Vinz
Holy crap, seriously, I'd quit. ;)
Helgi Hrafn Gunnarsson
LOL! Is this even real???
rmx
I have seen reverse-indented comments (but not statements)
finnw
You're kidding, right? This cannot be true ... In case it really is I propose to put the culprit in jail ...
Marius Schulz
+84  A: 

Forbidden:

while (true) {

Allowed:

for (;;) {
bh213
I read somewhere that used to be that some compilers would generate a CMP and a JME (or equiv) instruction for the first example, and just an unconditional JMP for the second. I doubt that is still the case.
Bernard
Others have argued that `for (;;) {` is a C Idiom for the first.
Robert P
If I understand modern, new-fangled smileys correctly, this standard is making the poor, overworked for statement cry!
Ben Blank
+1 comment @ Ben Blank
johnc
This is a de facto rule here. VC6 issues a compiler warning about while(true), but not about for(;;). Otherwise they're equivalent. So we pick the warning-free one.
user9876
Bjarne S. said in his book, "for (;;) should be read as forever". If it's good enough for the creator of C++, it should be good enough for you. :-)
Frank Krueger
Somewhat related questions (both mine): http://stackoverflow.com/questions/224138/infinite-loops-top-or-bottom and http://stackoverflow.com/questions/224421/constant-value-in-conditional-expression
CesarB
In the very first C program I worked on, someone had added #define ever (;;) so you could say "for ever {...}"
James Curran
there is a reason for it: while (true) {...} generates a warning on some compilers
Rom
Most code written targets a particular compiler suite - have your makefile squash that warning, and then then they're equivalent.
Dathan
Everyone knows for (;;) is much faster and less error-prone ;)
JoelFan
I... what? while(true) looks and flows nicer than for(;;).
TheLQ
Forced on us: #define EVER (;;) ... for EVER { ...
squelart
+38  A: 

Back in my C++ days we were not allowed to use ==,>=, <=,&&, etc. there were macros for this ...

if (bob EQ 7 AND alice LEQ 10)
{
   // blah
}

this was obviously to deal with the "old accidental assignment in conditional bug", however we also had the rule "put constants before variables", so

if (NULL EQ ptr); //ok
if (ptr EQ NULL); //not ok

Just remembered, the simplest coding standard I ever heard was "Write code as if the next maintainer is a vicious psychopath who knows where you live."

adam straughan
Ha. I like that.
Paul Nathan
rofl .. writing fortran in C.
Robert Paulson
i still do null == variable in c#. i know i don't need to worry about it, but i can't help myself. if I see it the other way I feel nervous. old habits die hard.
Troy Howard
The last one about the psychopath would get some people killed almost immediately.
TURBOxSPOOL
+1 for the vicious psychopath.
rcollyer
+3  A: 

Writing methods comments with pointless information for almost all methods.

Not allowing multiple exit points from a method.

Hungarian notation for all variables, enums, structures and even classes, e.g. iMyInt, tagMySturcture, eMyEnum and CMyClass.

I kind of like single exit points... then again, I'm a paradigm purist...
Brian Postow
I always hated my CS (Java) requirements that all methods be fully commented, even something like `int getX(){ return this.x; }`
Wayne Werner
Keeping single exit points makes perfect sense. I once had to fix a library that did my LPT port communication (couldn't be bothered to figure out how Windows did access to hardware), because it was badly leaking memory for each request. Turned out the author (probably) first made a general function template with malloc() and free() in it, and then (by omission?) added a second return point that directly returned the driver call's (which used the structure) result. Need I add that this new return point was inbetween allocation and freeing? *shudder*
Egon_Freeman
+168  A: 

I once worked under the tyranny of the Mighty VB King.

The VB King was the pure master of MS Excel and VBA, as well as databases (Hence his surname : He played with Excel while the developers worked with compilers, and challenging him on databases could have detrimental effects on your career...).

Of course, his immense skills gave him an unique vision of development problems and project management solutions: While not exactly coding standards in the strictest sense, the VB King regularly had new ideas about "coding standards" and "best practices" he tried (and oftentimes succeeded) to impose on us. For example:

  • All C/C++ arrays shall start at index 1, instead of 0. Indeed, the use of 0 as first index of an array is obsolete, and has been superseded by Visual Basic 6's insightful array index management.

  • All functions shall return an error code: There are no exceptions in VB6, so why would we need them at all? (i.e. in C++)

  • Since "All functions shall return an error code" is not practical for functions returning meaningful types, all functions shall have an error code as first [in/out] parameter.

  • All our code will check the error codes (this led to the worst case of VBScript if-indentation I ever saw in my career... Of course, as the "else" clauses were never handled, no error was actually found until too late).

  • Since we're working with C++/COM, starting this very day, we will code all our DOM utility functions in Visual Basic.

  • ASP 115 errors are evil. For this reason, we will use On Error Resume Next in our VBScript/ASP code to avoid them.

  • XSL-T is an object oriented language. Use inheritance to resolve your problems (dumb surprise almost broke my jaw open this one day).

  • Exceptions are not used, and thus should be removed. For this reason, we will uncheck the checkbox asking for destructor call in case of exception unwinding (it took days for an expert to find the cause of all those memory leaks, and he almost went berserk when he found out they had willingly ignored (and hidden) his technical note about checking the option again, sent handfuls of weeks before).

  • catch all exceptions in the COM interface of our COM modules, and dispose them silently (this way, instead of crashing, a module would only appear to be faster... Shiny!... As we used the über error handling described above, it even took us some time to understand what was really happening... You can't have both speed and correct results, can you?).

  • Starting today, our code base will split into four branches. We will manage their synchronization and integrate all bug corrections/evolutions by hand.

All but the C/C++ arrays, VB DOM utility functions and XSL-T as OOP language were implemented despite our protests. Of course, over the time, some were discovered, ahem, broken, and abandoned altogether.

Of course, the VB King credibility never suffered for that: Among the higher management, he remained a "top gun" technical expert...

This produced some amusing side effects, as you can see by following the link http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered/216744#216744

paercebal
Re: 1-indexing. Sometimes you just have to stand up and say something strong like "that's stupid and wrong". Draw a line in the sand. Forget placating egos and just say it. I can almost guarantee that every other worthwhile programmer will immediately start nodding and joining in.
Just Some Guy
Of the 10 points I mentionned, 7 points were implemented despite protests. The C/C++ array at 1, the DOM in VB and the XSL-T language as a OOP language were either refused (1 and 2) or simply irrealistic (2). I mentionned all the points to show how deep the VB King madness/stupidity went... :-p ...
paercebal
James Curran
For completeness sakes, yes, you need... :-p ... The fact is my Basic days were well over (I played with QBasic before moving to C) at the time the proposition was considered... I was unaware the OPTION BASE default was zero in VB, and the VB-King never mentioned it (did he even know it?)...:-p ..
paercebal
link to 'best comment' no longer works, unfortunately...
Jakub Narębski
@Jakub Link corrected.
paercebal
WTF, atrocious spelling!
jrista
@jrista: If YOU ARE NOT commenting the spelling of my text, please ignore the following ... ... ... ... ... ... ... ... If you are commenting my text, please consider (1) proposing corrections, (2) correcting the spelling yourself, or (3) Consider that not every developer in the world (far from it) are native english speaker, so I guess tolerating incorrect spelling is the minimum you can do, or prove you can do better by sending me the correct translation IN FRENCH... ^_^ ...
paercebal
If this guy were my boss, I would have gone straight to every member of higher management with a well-written and documented list of complaints and gotten him fired. -1 for not having the balls to stand up for yourself.
muusbolla
@muusbolla: Who told you we did not complain? It escalated until a delegation of two (including me) went straight to the CEO to explain the problem. But I'm sorry to have to tell you there is a difference between a idealistic world, where justice reigns, and the real world, where some bosses believe "the management is never wrong, even when it is", and will crush anyone that will dare to contradict that dogma. The only happy souvenir I have from that time is the day I resigned, almost three years ago, and I am a happier man since that day. Anyway, if true, your downmod reason is lame. Sorry.
paercebal
@paercebal: En générale, c'est correctement écrit, sauf que quelques petits erreurs: «squatch»: ça doit être «squash»; «this one day»: en ce context-là, on dirait «that day»; «stocked procedures»: «stock procedures»; «chocked» s'écrit «choked». Aussi, dans les commentaires, vous utilisez °mentionned», ce qui doit être «mentioned» Mais vraiment, tout ça ne justifie pas une telle plainte. Au contraire, vous y montrez une excellente maîtrise de l'anglais; félicitations!
intuited
+67  A: 

We were doing a C++ project and the team lead was a Pascal guy.

So we had a coding standard include file to redefine all that pesky C and C++ syntax:

#define BEGIN {
#define END }

but wait there's more!

#define ENDIF }
#define CASE switch

etc. It's hard to remember after all this time.

This took what would have been perfectly readable C++ code and made it illegible to anyone except the team lead.

We also had to use reverse Hungarian notation, i.e.

MyClass *class_pt  // pt = pointer to type

UINT32 maxHops_u   // u = uint32

although oddly I grew to like this.

billmcc
Building unmaintainable code for the future
rshimoda
Hungarian notation done right is okay. Done wrong... ick. A proper type system beats both.
Thelema
You know, I think I'm with you on that. The hungarian warts aren't nearly so objectionable when tacked onto the end like that.
T.E.D.
haha takes me back to the days when I switched from Pascal to C++ (about 16 years ago). Every time I saw a { I had to mentally tell myself "{ means BEGIN". At least for me it was just in my head.
thomasrutter
Wasn't there an old shell that was written entirely like this? Basically to the point where it didn't even resemble C.
TURBOxSPOOL
I can understand the begin/end stuff--{} look too much like ()!
Loren Pechtel
When I worked in MS VC++ support, we had several customers submit repro code written like this. It took a while for us to realize it was actually in C++ (they didn't include the #defines).
JBRWilkinson
+1  A: 

Postfixing _ to member variables. e.g.

int numberofCycles_;

This was in C++ on an open source project with a couple of developers. The main side effect was not knowing that a variable had class scope until getting to the end of the name. Not something I had thought much about before, but clearly backwards.

Jason Sundram
I'm unconvinced by the need to distinguish member variables at all, but if you're going to the beginning is obviously the place for it.
Mark Baker
names beginning with _ are reserved for the implementation. trailing underscore is a convention popular in the STL.
ASk
+8  A: 

One that no one has mentioned is being forced to write unit tests for classes that are brainless getters and setters.

moffdub
I don't see this as a problem. It's a lot nicer to have this type of test and find that you made a simple mistake instead of having to spend significant time debugging a larger unit/integration test to find it. Besides, you can probably automate/template these tests if they're that bad.
matt b
I failed to mention that our IDE has a menu item titled "Generate Getters and Setters..."
moffdub
in that case, write yourself a script "Generate Getter- and SetterTests".
Tetha
They need to be tested. I was driven absolutely nuts by a bug eons ago--the answer turned out to be in the runtime library, a piece of code that amounted to a setter. To compound it, there was a bug in the debugger (continued)
Loren Pechtel
Step through the code and it would work correctly. Execute it and you almost certainly got a protection violation. (The debugger swallowed the error and somehow produced a working result. This was possible as the data was correct, just not valid in a segment register.)
Loren Pechtel
Shouldn't the setters and constructors be checking to make sure their inputs are legal and it leaves the object in a valid state?
Barry Brown
Of course not! "The database does that." (actual quote from co-worker)
moffdub
@moffdub +1 sarcasm
Chris Kaminski
+10  A: 

The team size was about a dozen. For C# methods we had to put a huge XML formatted function before every function. I don't remember the format exactly but it involved XML tags nested about three to five levels deep. Here's a sketch from memory of the comment.

/// <comment>
/// </comment>
/// <table>
///    <thead>
///       <tcolumns>
///          <column>Date</column>
///          <column>Modified By</column>
///          <column>Comment</column>
///       </tcolumns>
///    </thead>
///    <rows>
///       <row>
///          <column>10/10/2006</column>
///          <column>Fred</column>
///          <column>Created function</column>
///       </row>
///    </rows>
/// <parameters>

I've got to stop there....

The downsides were many.

  • Files were made up mostly of comments.
  • We were not using our version control system for tracking changes to files.
  • Writing many small functions hurt readability.
  • Lots of scrolling.
  • Some people did not update the comments.

I used a code snippet (Emacs YAS) to add this code to my methods.

Tim Stewart
XML formatted anything in code hurts readability. To be used at the head of every single function, thats just horrible
TheLQ
+2  A: 

I am not allowed to use this-> to reference local variables in our c++ code...

Hans
Maybe you mean member variables? BTW, my company does not like this either.
JimDaniel
Oops, yes that is indeed what I meant. What reasons are you given? I just a "I don't like it" during code-reviews.
Hans
so... (*this).such_and_such?
TokenMacGuy
I think the reason behind this rule is to avoid having arguments and local variables with the same name as members.
Alexandru
+24  A: 

We had to sort all the functions in classes alphabetically, to make them "easier to find". Never mind the ide had a drop down. That was too many clicks.

(same tech lead wrote an app to remove all comments from our source code).

Nat
Well sure, 'cause comments are just clutter, after all... and think how many cycles the pre-processor saves at compile time! (The app is even funnier than the rule. Good one.)
ojrac
Of course! Developers are supposed to write code, not waste time writing comments :)
DR
Yeah! And comments make the build slower!
Greg D
Did that person actually use the IDE? I remember the ordering suggestion back in the days before IDEs....Have not heard much since.
TheJacobTaylor
Yep, but that involved click instead of keyboard :)
Nat
Nevertheless I think is a good rule to sort members by type (fields, properties, methods) and by name
abatishchev
Which would make sense.
Nat
@Nat: Any rule without sense is evil without doubt! :)
abatishchev
I sort methods, members, etc. alphabetically within their respective groups, in both header and source...but only because I'm obsessive.
Jon Purdy
This is not so silly if you use paper printouts for code reviews
finnw
+7  A: 

I once had to spell out all acronyms, even industry standard ones such as OpenGL. Variable names such as glu were not good, but we had to use graphicsLibraryUtility.

I hope you didn't use any software from GNU = "GNU is Not Unix".
Justsalt
+43  A: 

Using generic numbered identifier names

At my current work we have two rules which are really mean:

Rule 1: Every time we create a new field in a database table we have to add additional reserve fields for future use. These reserve fields are numbered (because no one knows which data they will hold some day) The next time we need a new field we first look for an unused reserve field.

So we end up with with customer.reserve_field_14 containing the e-mail address of the customer.

At one day our boss thought about introducing reserve tables, but fortunatly we could convince him not to do it.

Rule 2: One of our products is written in VB6 and VB6 has a limit of the total count of different identifiers and since the code is very large, we constantly run into this limit. As a "solution" all local variable names are numbered:

  • Lvarlong1
  • Lvarlong2
  • Lvarstr1
  • ...

Although that effectively circumvents the identifier limit, these two rules combined lead to beautiful code like this:

...

If Lvarbool1 Then
  Lvarbool2 = True
End If

If Lvarbool2 Or Lvarstr1 <> Lvarstr5 Then
  db.Execute("DELETE FROM customer WHERE " _ 
      & "reserve_field_12 = '" & Lvarstr1 & "'")
End If

...

You can imagine how hard it is to fix old or someone else's code...

Latest update: Now we are also using "reserve procedures" for private members:

Private Sub LSub1(Lvarlong1 As Long, Lvarstr1 As String)
  If Lvarlong1 >= 0 Then 
    Lvarbool1 = LFunc1(Lvarstr1)
  Else
    Lvarbool1 = LFunc6()
  End If
  If Lvarbool1 Then
    LSub4 Lvarstr1
  End If
End Sub

EDIT: It seems that this code pattern is becoming more and more popular. See this The Daily WTF post to learn more: Astigmatism.

DR
No kidding. I bet it took forever to go through and remove all those SQL injections. ;-)
Just Some Guy
That is pure evilness. I am sure your boss/TL is an overlord just waiting for his opportunity.
Manuel Ferreria
Actually he is pretty nice in person and a good business man, but one would never know from these coding rules... :)
DR
omg, who the hell would come up with rules like this??? most importantly: how the hell does your team manage to code??
hasen j
RE: Rule 1; Does that mean your DB queries are like "SELECT * FROM customer"? (Yes, I prescribe to the school of thought that keywords should be uppercase)
Pat
I'm not sure I understand your question (I'm not a native speaker) My personal queries are like that, because I find it easier to read, but that's not a rule. Is something wrong about it?
DR
I think he meant that you would select all fields by default so you got all the 'reserve' fields as well, without needing to specify them all.
TURBOxSPOOL
maibe you could use code preprosessing, where you would write your code using meaningfull variables names and then replace it with the "correct ones" before compilingsomegtinh like '%s/email/reserve_field_12/g' ;)
João Portela
Can't fathom a possible reason for adding RESERVE fields until they are needed. (unless the table actually stored some type of application-configured data)
BradC
The problem is, that on every database 1-5% of the customers have problems (mostly corrupted databases, Did I mention we have to work with Access/Jet?) Also the "migration tool" is somewhat fragile, so that we are going to avoid database updates, unless they become absolutly necessary...
DR
I imagine your dev team must be masters of reverse engineering
Longpoke
cool obfuscation.
Behrooz
How do numbered local variable names solve the problem? You still have the same number of identifiers... only relabelled. I don't get it.
trinithis
@trinithis: It's the number of *unique* identifiers which is limited.
DR
You are creating obfuscated code by hand!!!
Carlos Muñoz
+4  A: 

In C++, we had to write explicitly everything that the compiler is supposed to write for us (default constructor, destructor, copy constructor, copy assignment operator) for every class. Looks like whoever wrote the standards was not very confident on the language.

Gorpik
Or the standard was written back in the days when compilers didn't do that reliably.
Chris Kaminski
+5  A: 

Perhaps one of the more frustrating situations I've encountered was where people insisted on prefixing Stored Procedures with the prefix "sp_".

If you don't know why this is a bad thing to do, check out this blog entry here!

In a nutshell, if SQL Server is looking for a Stored Procedure with an sp_ prefix, it will check the master database first (which it won't find unless the SP is actually in the master database). Assuming it isn't in the master DB, SQL Server assumes the SP isn't in the cache and therefore recompiles it.

It may sound like a small thing, but it adds up in high volume or busy database server environments!

RobS
I didn't know that, but this convention annoys me just because it becomes impossible to jump anywhere in the long stored proc list. Everything starts with S.
Kyralessa
+6  A: 

The worst I've experienced was to do with code inspections. For some reason even though we had and used the diff tool of our vcs to see what had changed, when you wanted your code inspected you had to surround your changes in a file/function with some comment blocks like so:

/*********...80charswide...***
 * START INSPECT
 */

 some changed code...

 /*
  * END INSPECT
  *********...80charswide...****/

After the inspection you'd have to go back and remove all those comment blocks before committing. ugh.

DarthNoodles
Maybe the person/group doing the inspections hated SVN?
TheLQ
+4  A: 

In a large group at my company, we use C++ almost exclusively. Passing by non-const reference is forbidden.

If you want to modify a parameter to a function, you must pass it by pointer.

We have an internal flame war over the pros (easier to identify function calls that can modify variables) and cons (ridiculousness; having to deal with possible NULL pointers when you want a parameter to be required) about once a year.

A: 

"The guys who wrote the compiler are probably a lot smarter than you so don't try something clever" is what one guide line document said (not quite literally).

Niklas Winde
This sounds perfectly reasonable to me. In this context, "something clever" refers to premature and misguided attempts at optimization that either make the program run even slower (by confusing the compiler's optimizer) or thoroughly obfuscate the code for a minuscule performance enhancement.
Tyler McHenry
you mean *attempted* minuscule performance enhancement. "clever optimizations" could actually end up being slower :)
jdizzle
+7  A: 

inserting line breaks
(//--------------------------------------------------------------------------------)
between methods in a c# project.

ha, I had to do that in college. Good times
mabwi
He he. Now, some IDE (like IntelliJ) can display such a line breaks, without modifying the source code itself...
romaintaz
And this improves readability how?
TheLQ
+64  A: 

The very strangest one I had, and one which took me quite some time to overthrow, was when the owner of our company demanded that our new product be IE only. If it could work on FireFox, that was OK, but it had to be IE only.

This might not sound too strange, except for one little flaw. All of the software was for a bespoke server software package, running on Linux, and all client boxes that our customer was buying were Linux. Short of trying to figure out how to get Wine (in those days, very unreliable) up and running on all of these boxes and seeing if we could get IE running and training their admins how to debug Wine problems, it simply wasn't possible to meet the owner's request. The problem was that he was doing the Web design and simply didn't know how to make Web sites compliant with FireFox.

It probably won't shock you to know that that our company went bankrupt.

Ovid
I would say, that is pretty strange.
Brad Gilbert
Three cheers for capitalism!
starblue
Yay for survival of the fittest...this guy didn't deserve to be running his own software business.
Mark Brittingham
The last sentence was great. How could someone be taken seriously when they make decisions like this?
TURBOxSPOOL
+7  A: 

Being forced to have only 1 return statement at the end of a method and making the code fall down to that.

Also not being able to re-use case statements in a switch and let it drop through; I had to write a convoluted script that did a sort of loop of the switch to handle both cases in the right order.

Lastly, when I started using C, I found it very odd to declare my variables at the top of a method and absolutely hated it. I'd spent a good couple of years in C++ and just declared them wherever I wanted; Unless for optimisation reasons I now declare all method variables at the top of a method with details of what they all do - makes maintenance A LOT easier.

widgisoft
+2  A: 

All documents in my company are version-controlled. So far, so good.

But for EVERY single file, upon first committing to CVS, you must immediately add two tags to it: CRE (for CREation) and DEV001 (for 1st DEVelopment cycle). As if it being the first version of the file itself wasn't enough.

After that, the process gets a bit more reasonable, fortunately.

schonarth
+23  A: 

Prefix tables with dbo_

Yes, as in dbo.dbo_tablename.

Stefan
LOL, I have a project right now that is sending to another company and that is the way they want the column names in the Excel files we are to send them. I knew that the names had to be the column names in their database (as they wouldn't let us replace them with names that actually made sense in context of the report.)
HLGEM
Because looking at dbo.tablename is such an eyesore...
TheLQ
What happens to tables not in `dbo`? :)
Christian Hayter
+4  A: 

I worked in a VB .NET shop three years ago, where the "technical lead" decreed that all methods accepting a reference type parameter (i.e., an object) must use ByRef instead of ByVal. I found this especially odd because they'd asked me the ByVal/ByRef-what's-the-difference question in my interview, and I explained how it worked for value types and for reference types.

His explanation for the practice: "Some of the newer, less-experienced devs will get confused otherwise."

At the time, I was the most recently hired, and it was my first permanent .NET job. And I wasn't confused by it.

Kyralessa
Ugh. Now I'm seeing this in my current job too: Methods that use *ref* on parameters because the methods change properties of the reference type passed in, and the developer didn't understand how reference types work.
Kyralessa
+1  A: 

The first language I used professionally was 4D. It supported interprocess variables prefixed by a <>, process variables with no prefixes and local variables which started with a $. All those prefixes (or lack thereof) are used by the compiler/interpreter to determine the variable's scope.

The actual strange coding standard was some sort of hungarian notation. The catch was that instead of naming variables based on their types, they had to be prefixed according to their scope.

Variables, whose scope were determined by their prefix, had to be prefixed with redundant information!

I don't dare ask the guy responsible for the standards why it had to be this way...

Alex Brault
+2  A: 

I ran into two rules that I really hated on a C job a few years ago:

  1. "One module per file," where "module" was defined as a C function.

  2. Function-local variables allowed only at the top of the function, so this sort of thing was illegal:

if (test)
{
   int i;
   ...
}
Those are both pretty horrible :)
Brian R. Bondy
The first rule actually makes sense for static libraries, where only the referenced objects will be linked in. Having one function per file avoids accidentally linking in unused functions.
CesarB
In general, I like the second rule! especially in C where you can't declare just anywhere...
Brian Postow
In Delphi you can only declare function-local variables at the top. It structures your code, I don't think it is bad.
tuinstoel
I've been bitten by bugs caused by #2 before. If you're declaring all local variables at the top, there's no scope restrictions for where it can be used or assigned. It's quite easy for a bug to slip in because a different variable was used rather than the one you really wanted (especially if you've copied, pasted and edited similar parts of the method). You might take a hit on structure, but declaring variables to the scope where they're used can prevent some bugs from even occurring.
InverseFalcon
@Brian Postow Its a bit late, but that is correct C code because the declaration is at the top of a block, that is, the braces of the if statements.
mathepic
+5  A: 

I absolutely hate it when someone doesn't use a naming convention. At where I worked, the lead developer (who I replaced) couldn't figure out if he wanted to use camelCase, or way_over_used_underscores. Personally, I hate the underscores and the camel case is easier to read, but it doesn't really matter as long as you keep to one standard.

PHP is especially bad at this, take a look at mysql_numrows which merges the two without the caps.

Malfist
In PHP, it helps with separation. mysql_numRows looks alot better than mysqlNumRows.
TheLQ
@TheLQ And mysql_num_rows looks a lot better than mysql_numRows and mysql_nrows is the best.
mathepic
+75  A: 

a friend of mine - we'll call him CodeMonkey - got his first job out of college [many years ago] doing in-house development in COBOL. His first program was rejected as 'not complying with our standards' because it used... [shudder!] nested IF statements

the coding standards banned the use of nested IF statements

now, CodeMonkey was not shy and was certain of his abilities, so he persisted in asking everyone up the chain and down the aisle why this rule existed. Most claimed they did not know, some made up stuff about 'readability', and finally one person remembered the original reason: the first version of the COBOL compiler they used had a bug and didn't handle nested IF statements correctly.

This compiler bug, of course, had been fixed for at least a decade, but no one had challenged the standards. [baaa!]

CodeMonkey was successful in getting the standards changed - eventually!

Steven A. Lowe
Steven, this reminds me the monkey experiment story :o) http://freekvermeulen.blogspot.com/2008/08/monkey-story-experiment-involved-5.html
Nick D
@[Nick D]: yes, me too - hence the code-name "CodeMonkey" ;-)
Steven A. Lowe
Or [Grandma's Cooking Secret](http://www.snopes.com/weddings/newlywed/secret.asp)...
detly
+11  A: 

Not quite a coding standard, but in 1998 I worked for a company where C++ was banned, in favour of C. This was because OO was considered too complex for the software engineers to grasp.

In our C code we were required to prefix all semi-colons with a space

int someInt = 5 ;

I could never find out a reason for this, but after a while it did grow on me.

Richard Ev
+1 for working with programmers that are afraid of OO
mabwi
Well, Linus has stated that C++ is a horrible language: http://thread.gmane.org/gmane.comp.version-control.git/57643/focus=57918
tuinstoel
I'm not impressed with Linus's ranting. He sounds very idealogical and biased. I'll stick with the STL - it's never broken for me.
Paul Nathan
I worked for a company in 2005 where C++ was eschewed in favor of C. (Because the default distro had a broken version of GCC, and clearly it was better to spend the extra man years to use C than it would have been to upgrade the compiler.)
Corey Porter
Actually I'd quite like to work for a company that eschews OO, just to get a break from working with OO zealots (the kind who think up some of the other stupid standards mentioned in this thread.)
finnw
@Paul Nathan: Linus did a great thing bringing us a GPLed Unix, but I think he's done some things under his benevolent dictatorship that have hamstrung the whole process. The completely unstable driver APIs, for one. You get one version of the API that's open sourced, and then it stops working (vmware, promise, adaptec) with a kernel update. It's annoying and counterproductive. I've been using C++ since 1993 - aside from some rough spots when the STL first came out, it's been rock solid.
Chris Kaminski
+6  A: 

Adding an 80 character comment at the end of each method so it is easy to find the end of the method. Like this:

void doSomething()
{
}
//----------------------------------------------------------------------------

The rationale being that:

  • some users don't use IDE's that have code folding (Ok I will give them that).
  • a space between methods is not clear since people may not follow the other coding standards about indenting and brace placement, hence it would be hard to find the end of a function. (Not releavent; if you need to add this because people don't follow your coding standard then why should they follow this one?)
Mark Thistle
+1 for the second part of the rationale.
David Thornley
The brace belongs at the beginning of the next available line. If people don't follow that, then they are probably going to be starving for work
TheLQ
Yeah, the second reason really does not make sense.
Johan
+5  A: 

SCORM for sure. (http://en.wikipedia.org/wiki/SCORM)

shogun
+4  A: 

I've been getting worked up over naming table columns after mysql keywords. It requires stupid column name escaping in every single query you write.

SELECT this, that, `key` FROM sometable WHERE such AND suchmore;

Just horrible.

Kris
SELECT `this`, `that`, `key` etc is an acceptable alternative, in my world anyway. I tend to quote names, but usually have to fix `tablename.columnname` with some regularity.
TokenMacGuy
+3  A: 

At the place I'm currently working, the official coding standard stipulates a maximum line length of eighty characters. The rational was to enable hard-copies of the code to be formatted. Needless to say, this led to very odd code layout. I've worked to eliminate this standard, mainly through the argument of 'when was the last time you made a hard-copy of code?' Readability now versus chance of making a hard-copy on an eighty column DMP?

Skizz

Skizz
This wasn't as bad when everyone used text terminals or 640x480 or 800x600 monitors and I frequently print out sections of code to review, but there is no need to make it a standard anymore. However, suggesting to keep it under 150 or so isn't bad practice.
CMPalmer
Lines too long? then you don't have enough monitors. My editor stretches across all three of my displays!
TokenMacGuy
@TokenMacGuy: sweet! Then you can finally have the mythic perfect method: `TheNewSuperClassObjectForTrainingFlightManagement myInstanceOfTheNewSuperClassObjectForTrainingFlightManagement = new TheNewSuperClassObjectForTrainingFlightManagement( TheNewSuperClassObjectForTrainingFlightManagementConfigurationOptionOne.FirstOption, TheNewSuperClassObjectForTrainingFlightManagementConfigurationOptionTwo.SecondOption);` That only takes up 400 columns or so!
Robert P
with 16:9 and 16:10 monitors standard now this is really an idiotic requirement.
fuzzy lollipop
Except that we're dealing with the human eye here, and excessively wide columns aren't easy to read.
David Thornley
The old 80 character limit needs to be abolished in favor of 140. 80 is too small, and 140 is quite large
TheLQ
I think 80 columns makes sense for most code, but standards that force an 81 character line to be split is a bit much IMO. I had a job like that once and it was annoying (actually, our limit was 72). Most good code naturally fits in < 80 columns but there are times when going a few over makes the code more readable rather than less.
Bryan Oakley
80 character is a very reasonable limit. The people who disagree probably edit in IDE's rather than terminals.
mathepic
+2  A: 

Although this wasn't at a job, we had a massive project for a class in college. One of the requirements was commenting every line of code in our application -- regardless of what it did... and each line had to be specific e.g.

int x=0; //declare variable x and assign it to 0

We weren't allowed to do this:

int x, y, z = 0; //declare and assign to 0

As it wasn't detailed enough. And that's not even following the naming conventions forced upon us.

Needless to say we spent a few hours going back through the code...

MunkiPhD
Wow, and I thought that *I* taught an extreme CS 1 class... We had no 1 letter variable names (just in CS 1) and comments for "every logical chunk"
Brian Postow
Yea, it was pretty absurd considering it was an upper level class - especially one where you had to know what you were doing considering the nature of the project.
MunkiPhD
You're not assigning x to 0 there... you're assigning 0 to x.
Kris
@ Kris - you're very correct. I probably would have lost 10 points on that if I had turned it in >.<
MunkiPhD
I would have told my prof to go suck himself... probably explains why my grades aren't the best.
muusbolla
In fact, you're not doing any assignment whatsoever there. That's an initialization, which is distinctly different from an assignment in both C and C++. 1000 points off!
Tyler McHenry
+10  A: 

(Probably only funny in the uk)

An insurer I worked at wanted a combination "P" or "L" to denote the scope, concatenated with hungarian for the type, on all properties.

The plus point was we had a property called pintMaster! Made us all fancy a drink.

Chris Needham
+1 'cause now I fancy a drink too!
ZJR
+1 ...and to people who enjoy UK shows :)
dr Hannibal Lecter
+2  A: 

At a major UK bank I was brought in to act as a design authority on a new .NET system.

Their rules state that the database tables had to be a maximum of 8 characters long, with the project code (a 5 digit code) as the prefix.

They were enforcing old DB2 rules onto Windows projects sigh

blowdart
+2  A: 

Only one variable can be declared per logical line. [Rational: Multiple declaration per line results in an inaccurate line-of-code count.]

Andy
*facepalm* That's amazingly inane. Condolences!
TokenMacGuy
The rule itself isn't that bad, at least in some languages. It's a decent rule for C++, for example. Most of my declarations are one to a line. The rationale, on the other hand, is amazingly stupid.
David Thornley
+20  A: 

At my first job, all C programs, no matter how simple or complex, had only four functions. You had the main, which called the other three functions in turn. I can't remember their names, but they were something along the lines of begin(), middle(), and end(). begin() opened files and database connections, end() closed them, and middle() did everything else. Needless to say, middle() was a very long function.

And just to make things even better, all variables had to be global.

One of my proudest memories of that job is having been part of the general revolt that led to the destruction of those standards.

abeger
I guess on paper in a meeting room it sounded good, but I pity the programmer who had to follow it
TheLQ
+2  A: 

No Hungarian whatsoever.

OK, you're thinking this is bad why? Well, because they considered this to be Hungarian:

int foo;
int *pFoo;
int **hFoo;

Now, any old-school Mac programmer will remember dealing with Handles and Ptrs. The above is the easiest way to tell them apart - Apple sample code is full of it, and Apple was hardly a hotbed of Hungarianism. And so when I had to write some old-school Mac code, naturally I did that, and got it shot down for being Hungarian.

But nobody could propose an alternate naming scheme that preserved the clarity of three variables referring to the same data in different ways, so I checked it in as-is.

How about: int foo; int *fooPtr; int **fooHdl;Now they even sort together!
Frank Szczerba
+4  A: 

I had to spell and grammar check my comments. They had to be complete sentences, properly capitalized and finished with a period.

Bryan Oakley
I always enforce this rule. I suppose it's due to my belief if the broken windows theory (being sloppy in one place encourages people to be sloppy in other places).
Sander
@Sander: That's belief *in* the broken windows theory. (Sorry, couldn't resist the irony.)
David Thornley
Eww... when I want to read a comment I want something short and easy to read, not an English Paper paragraph.
TheLQ
Spell check, sure, and *reasonable* grammar is a good thing. Makes it easier to read. But full sentences not (always) so much.
Wayne Werner
+23  A: 

In 1987 or so, I took a job with a company that hired me because I was one of a small handful of people who knew how to use Revelation. Revelation, if you've never heard of it, was essentially a PC-based implementation of the Pick operating system - which, if you've never heard of it, got its name from its inventor, the fabulously-named Dick Pick. Much can be said about the Pick OS, most of it good. A number of supermini vendors (Prime and MIPS, at least) used Pick, or their own custom implementations of it.

This company was a Prime shop, and for their in-house systems they used Information. (No, that was really its name: it was Prime's implementation of Pick.) They had a contract with the state to build a PC-based system, and had put about a year into their Revelation project before the guy doing all the work, who was also their MIS director, decided he couldn't do both jobs anymore and hired me.

At any rate, he'd established a number of coding standards for their Prime-based software, many of which derived from two basic conditions: 1) the use of 80-column dumb terminals, and 2) the fact that since Prime didn't have a visual editor, he'd written his own. Because of the magic portability of Pick code, he'd brought his editor down into Revelation, and had built the entire project on the PC using it.

Revelation, of course, being PC-based, had a perfectly good full-screen editor, and didn't object when you went past column 80. However, for the first several months I was there, he insisted that I use his editor and his standards.

So, the first standard was that every line of code had to be commented. Every line. No exceptions. His rationale for that was that even if your comment said exactly what you had just written in the code, having to comment it meant you at least thought about the line twice. Also, as he cheerfully pointed out, he'd added a command to the editor that formatted each line of code so that you could put an end-of-line comment.

Oh, yes. When you commented every line of code, it was with end-of-line comments. In short, the first 64 characters of each line were for code, then there was a semicolon, and then you had 15 characters to describe what your 64 characters did. In short, we were using an assembly language convention to format our Pick/Basic code. This led to things that looked like this:

EVENT.LIST[DATE.INDEX][-1] = _         ;ADD THE MOST RECENT EVENT
   EVENTS[LEN(EVENTS)]                 ;TO THE END OF EVENT LIST

(Actually, after 20 years I have finally forgotten R/Basic's line-continuation syntax, so it may have looked different. But you get the idea.)

Additionally, whenever you had to insert multiline comments, the rule was that you use a flower box:

************************************************************************
**  IN CASE YOU NEVER HEARD OF ONE, OR COULDN'T GUESS FROM ITS NAME,  **
**  THIS IS A FLOWER BOX.                                             **
************************************************************************

Yes, those closing asterisks on each line were required. After all, if you used his editor, it was just a simple editor command to insert a flower box.

Getting him to relent and let me use Revelation's built-in editor was quite a battle. At first he was insistent, simply because those were the rules. When I objected that a) I already knew the Revelation editor b) it was substantially more functional than his editor, c) other Revelation developers would have the same perspective, he retorted that if I didn't train on his editor I wouldn't ever be able to work on the Prime codebase, which, as we both knew, was not going to happen as long as hell remained unfrozen over. Finally he gave in.

But the coding standards were the last to go. The flower-box comments in particular were a stupid waste of time, and he fought me tooth and nail on them, saying that if I'd just use the right editor maintaining them would be perfectly easy. (The whole thing got pretty passive-aggressive.) Finally I quietly gave in, and from then on all of the code I brought to code reviews had his precious flower-box comments.

One day, several months into the job, when I'd pretty much proven myself more than competent (especially in comparison with the remarkable parade of other coders that passed through that office while I worked there), he was looking over my shoulder as I worked, and he noticed I wasn't using flower-box comments. Oh, I said, I wrote a source-code formatter that converts my comments into your style when I print them out. It's easier than maintaining them in the editor. He opened his mouth, thought for a moment, closed it, went away, and we never talked about coding standards again. Both of our jobs got easier after that.

Robert Rossney
+1 for the comment formatter when printing
BradC
The flower box should NEVER be overused. I hate it when I'm reading along code, okay nice comment, then see a flower box screaming "THIS DOES THIS AND THIS AND THIS"
TheLQ
+8  A: 

In Java, when contracting somewhere that shall remain nameless, Interfaces were banned. The logic? The guy in charge couldn't find implementing classes with Eclipse...

Also banned - anonymous inner classes, on the grounds that the guy in charge didn't know what they were. Which made implementing a Swing GUI all kinds of fun.

I feel very bad for you.
Isaac Waller
Perhaps http://www.eclipse.org/documentation/ ?
TheLQ
+2  A: 

The worst is a nameless place I still earn money from, there are no standards. Every program is new adventure.

Fortunately another contractor and I are slowly training the real employees and forcing some structure on the mess.

dverespey
+11  A: 

Wow -- this brings back so many memories of one particular place that I worked: Arizona Department of Transportation.

There was a project manager there that didn't understand object-based programming (and didn't want to understand it). She was convinced that object-based programming was a fad, and refused to let anybody check-in code that used any kind of object based programming.

(Seriously -- she actually spent a lot of her day reviewing code that we had checked-in to Visual SourceSafe just to make sure we weren't breaking the rules).

Considering Visual Basic 4 had just released (this was about 12 years ago), and considering that the Windows forms application we were building in VB4 used objects to describe the forms, this made development ... complicated.

A buddy of mine actually tried to get around this problem by encapsulating his 'object code' inside dummy 'forms' and she eventually caught on that he was just (* gasp *) hiding his objects!

Needless to say, I only lasted about 3 months there.

Gosh, I disliked that woman's thinking.

Dan Esparza
It baffles me how such people even get hired????
Roberto Sebestyen
Hiring decisions are often made by people with no technical skills, and certain sorts of horribly incompetent people are great at bluffing these interviews with lots of snazzy buzzwords.
Tyler McHenry
@Roberto: Almost certainly seniority. She had presumably started with the state a long time ago, and had been promoted through seniority. This guarantees that the management does have a lot of experience, but not that it's anywhere near the right kind of experience.
David Thornley
Actually -- she was a contractor. Didn't have much senority in terms of years.
Dan Esparza
OOP is a fad. Hmm. http://en.wikipedia.org/wiki/Object-oriented_programming#OOP_languages
TheLQ
I'm sure she probably thinks Wikipedia is either inaccurate or a fad, too. ;-)
Dan Esparza
I'm amazed. I bet she ended up with a pretty good grasp of OOP anyway in order to detect all the obfuscations used to get round her.
Christian Hayter
LOL. I'd like to think so ... but she sure didn't let on.
Dan Esparza
+5  A: 

This isn't a coding standard issue, but is surely a tale of restrictive thinking. We had completed a short 4 week project in no less than 7 weeks. The schedule was loosely based on guestimating a feature list. The development process consisted of coding furiously. During the postmortem I suggested using milestones and breaking feature requests into tasks. Incredibly, my director dismissed my ideas, saying that because it was such a short project, we didn't need to use milestones or tasks, and asked for other suggestions. The room fell silent.

Language: Java, C++, HTML Team size: Two teams, totaling 10 engineers Which ill effects it caused you and your team: I felt like I was caught in a Dilbert cartoon.

For very small projects, it might be a bit of overkill. But for any developer team, set tasks and milestones make life EASIER!
TheLQ
+4  A: 

Giving numbers to our tables, like tbl47_[some name]

David Filip
Now its easy to tell when that table was added!
TheLQ
+1  A: 

In my last job, my supervisor always enforced Murphy's Law:

"Anything that can go wrong will go wrong."

I guess it was so we didn't slack off doing some quick fixes in the code or something like that. And now I constantly have that phrase in my head.

Carlo
Why is this a strange at all?
SDX2000
@SDX2000 hahaha you're right, it isn't strange at all.
Carlo
+4  A: 

My coding standards gripes are pretty tame compared to some of the heinous stuff I've seen here, but here goes:

I was on a project where some of the developers insisted on the most peculiar form of indenting I've ever seen:

if (condition)
   {
      x++;
      printf("Hello condition!\n");
   }
else
   {
      y++;
   }

We were developing for an embedded environment with a really rotten debugger. In fact, printf(), hexdump() and the mapfile were the preferred method of debugging. This of course meant using static was forbidden and all global variables and functions had to be of the form modulename_variablename.

Checking in code with warnings was forbidden (not such a bad thing), but the compiler would warn about any conditional that was constant. Therefore, the old macro/statement trick of do { something(); } while(0) was forbidden.

Lastly, leaving a trailing comma on a enumerator list or initializer was considered lazy, and thus forbidden:

enum debuglevel
   {
      NONE,
      FATAL,
      WARNING,
      VERBOSE,   // Naughty, naughty!
   };

As I've said, rather tame. But as a follower of "The Ten Commandments for C Programmers", I found the unconventional bracing style absolutely maddening.

That brace style is *insane*. I don't care if you're in the `{\n` camp (me) or the `\n{` camp, that's a great compromise that everyone is sure to hate.
Wayne Werner
+20  A: 

An externally-written C coding standard that had the rule 'don't rely on built in operator precedence, always use brackets'

Fair enough, the obvious intent was to ban:

a = 3 + 6 * 2;

in favour of:

a = 3 + (6 * 2);

Thing was, this was enforced by a tool that followed the C syntax rules that '=', '==', '.' and array access are operators. So code like:

a[i].x += b[i].y + d - 7;

had to be written as:

((a[i]).x) += (((b[i]).y + d) - 7);
soru
maybe (((a)[(i)]).x) += (((((b)[(i)]).y) + (d)) - (7)); ?
Behrooz
I guess that would be MISRA?
finnw
+1  A: 

My old boss insisted that we use constants instead of enums but never gave a reason and in all the scenarios these were used an enum made more sense.

The better one though was insisting that all table names be singular and then making the classes in code singular as well. But not only did they represent the object, such as a user or group, they also represented the table and contained all of the CRUD for that table and numerous other actions. But wait, there’s more! They also had to contain a publicly visible name/value collection so that way you could get the properties with an indexer, by column name, just in case you added a new column but didn't want to add in a new property. There were a bunch of other "must do's" that not only didn't make sense, but put a big performance hit on the code as well. I could try to point them all out but the code speaks for itself and sadly this is almost an exact copy of the User class I just pulled out of an old archive folder:

public class Record
{
    private string tablename;
    private Database database;

    public NameValueCollection Fields;

    public Record(string TableName) : this(TableName, null) { }
    public Record(string TableName, Database db)
    {
     tablename = TableName;
     database = db;
    }

    public string TableName
    {
     get { return tablename; }
    }

    public ulong ID
    {
     get { return GetULong("ID"); }
     set { Fields["ID"] = value.ToString(); }

    }

    public virtual ulong GetULong(string field)
    {
     try { return ulong.Parse(this[field]); }
     catch(Exception) { return 0; }
    }

    public virtual bool Change()
    {
     InitializeDB(); // opens the connection
     // loop over the Fields object and build an update query
     DisposeDB(); // closes the connection
     // return the status
    }

    public virtual bool Create()
    {
     // works almost just like the Change method
    }

    public virtual bool Read()
    {
     InitializeDB(); // opens the connection
     // use the value of the ID property to build a select query
     // populate the Fields collection with the columns/values if the read was successful
     DisposeDB(); // closes the connection
     // return the status 
    }
}

public class User
{
    public User() : base("User") { }
    public User(Database db) : base("User", db) { }

    public string Username
    {
     get { return Fields["Username"]; }
     set
     {
      Fields["Username"] = value.ToString(); // yes, there really is a redundant ToString call
     }
    }
}

sorry if this double posts, first time around I might not of been human or maybe the site just has a limit to how bad code can be to be posted

Brian Surowiec
singular table names are good Relation Database design tenents and go back to the beginning of RDBMS times. Now the properties dictionary really is a WTF. And this is a bastardization of the "ActiveRecord" pattern that has been proven NOT to scale.
fuzzy lollipop
+4  A: 

Marking private variables with an _ just to make sure that we know we are dealing with private variables within the class. Then using php's magic methods __get and __set to provide access to each of the variables as if they were public anyway...

SeanJA
I've seen that in a few libraries. Kinda strange, but isn't all that bad
TheLQ
I 100% prefer python's `self.` requirement to typing a single _. There's something much less graceful about _ (plus the fact that it can mean different things to different languages. `self` is pretty obvious to any English-speaker.)
Wayne Werner
+3  A: 

While coding for a VB project I was asked to add the following comment section for each of the methods 'Module Name 'Module Description 'Parameters and description of each parameter 'Called by 'Calls

While I found the rest quite alright but I was against the last two, the reason I argued was the as the project becomes large it will become difficult to maintain. If we are creating the library function then we can never be able to maintain Called by. We were small team of 6, so the argument made by manager was that since you are going to call the functions this should be maintained. Anyway I had to give up this argument as the manager was adamant. The result was as expected, as the project become larger no one cared to maintain Called by and Calls.

+31  A: 

When I started working at one place, and started entering my code into the source control, my boss suddenly came up to me, and asked me to stop committing so much. He told me it is discouraged to do more than 1 commit per-day for a developer because it litters the source control. I simply gaped at him...

Later I understood that the reason he even came up to me about it is because the SVN server would send him (and 10 more high executives) a mail for each commit someone makes. And by littering the source control I guessed he ment his mailbox.

Avihu Turzion
Highlight email, click delete, done
TheLQ
I am definitely **not** a fan of so-called "chunky check-ins". Commit when your change is complete, simple as that. I also like to commit at the end of the work day as it enforces in my mind that my code should be compilable and be at least runnable with the rest of the project for other coders the next morning.
Jesse C. Slicer
Get the best of both worlds - Commit to your local branch whenever you dont want to lose something. Rebase and squash those commits when you're ready to put them into master. (forgive the git terminology - I'm sure its possible in mercurial and a bunch of other systems too)
Michael Anderson
I agree with all of the above. It's a rooted problem of approaching version control. It has no technological solution. I considered moving to git-svn, which would enable me to work with a local repository and then push things to the SVN repository, but that would have just sent the mails for all of my day's commits in one huge batch, and would have solved nothing for my bosses.
Avihu Turzion
+1  A: 

Capitalizing Acronyms

DO capitalize both characters of two-character acronyms except the first word of a camel-cased identifier.

System.IO
public void StartIO(Stream ioStream)

DO capitalize only the first character of acronyms with three or more characters except the first word of a camel-cased identifier.

System.Xml
public void ProcessHtmlTag(string htmlTag)

DO NOT capitalize any of the characters of any acronyms, whatever their length, at the beginning of a camel-cased identifier.

nobar
Fair use (I'm poking fun) -- "Framework Design Guidelines", Cwalina and Abrams
nobar
By the way, one of the projects I'm on does check for this using "FxCop". I get a lot of warnings about naming conventions, so I wouldn't know if I got any important warnings. My component is not part of any customer-facing "framework".
nobar
Well, I don't know about how I should feel about this. I do often mistakenly type document.getElementByID instead of document.getElementById (notice the capitalization of the last D) but ID is NOT an acronym.
Frank
+2  A: 

having to put m_ prefix on java instance variables and g_ prefix on java static variables, most un-Java idiot cruft I have ever had to deal with.

fuzzy lollipop
+6  A: 

The last place I worked was primarily a C++ shop, and before I was hired my boss (who was the director of research and development) had issued a decree that "dynamic memory allocation is not allowed". No "new", not even a "malloc" -- because "those can lead to memory leaks if a developer forgets the corresponding delete/free operation". As a corollary to this particular rule, "pointers are also not allowed" (although references were totally acceptable, being both awesome and safe).

I repealed those rules (as opposed to, say, rewriting all our software in other languages) but I did have to add a few awesome rules of my own, like "you may not launch a new thread without written approval from someone qualified to do that sort of thing" based on an unfortunate series of code reviews (sigh).

Rob Pelletier
haha that's pretty crippling
Brian R. Bondy
So... should programming not be allowed because it can lead to segfaults?
Wayne Werner
+3  A: 

On one of my first jobs the boss said that we should always use fully qualified type names in C# and forbid usings, since we should always know which type we're using when declaring variable, parameter, etc.

Dmitriy Matveev
+7  A: 

I once worked on a VB.NET project where every method body was wrapped in the following Try...Catch block:

Public Sub MyMethod()
    Try
        ' Whatever
    Catch Ex As Exception
        Throw New Exception("MyClass::MyMethod::" + Ex.ToString())
    End Try
End Sub

Those who do not understand Exception.StackTrace are doomed to reinvent it, badly.

jammycakes
That will be a "guru" who knows about all this new-fangled exception handling but still thinks in `On Error GoTo`. :-(
Christian Hayter
+7  A: 

Once I had to do a little DLL out of my team and when it was done I had to redo the job because I shouldn't have had used "else" in the code. When I asked why I was instructed not to ask why, but the leader of the other team just "didn't get the else stuff".

Eder Gusatto
Didn't get the else stuff...? And this guy got hired how?
TheLQ
I can say he came from the Cobol age and fell down in a OO project. I guess he came thru a portal directly from the 70's... ;) I remember that I put a huge comment explaining why I did that without "else", I didn't want to be blamed for that hidious code.
Eder Gusatto
should have just done "else if True". Same function as else, and maybe the idiot can grasp that.
Wayne Werner
+3  A: 

The Project i work for hard coding is a strict NO..So we were forced to hash define as below

#define 1 ONE

Vaibhav
<shudder>This is sooo bad.</shudder>
Luc
+2  A: 

Not being allowed to use Pointers or GOTO! (In C, none-the-less!) Thankfully this was merely a "software engineering" class, which I was able to graduate and then enter the "real world".

Arafangion
Banning pointers is bad. Banning GOTO makes perfect sense. Shame on you for wanting to use goto.
abelenky
It's C. C doesn't exactly have the glut of flow-control (exception handling, for example) that other higher-level langauges have. Sometimes GOTO makes for an elegant implementation in C.
Arafangion
Labeled goto:s are OK, although usually avoidable. Most commonly you're doing too much in too few lines of code if you need goto:s for flow control. But then again it's C...
Esko
"C doesn't exactly have the glut of flow-control" what language? what glut? Please give some examples.
SDX2000
SDX2000: Do you mean to ask for examples of flow control found in other languages but not in C? I've mentioned that the language is C.
Arafangion
Well, It makes perfect sense to forbid such things; But did you just say that you were forbidden to do so in a programming lecture?What tha heck? When you are learning something it's meant that you really should burn your finger so that you have some experience.Probably the teacher was unsure about these himself..
Frank
The general philosophy at that place was that "Pointers and GOTO are evil". Nevermind that pointers aren't optional in C.
Arafangion
Anybody who, in a modern language, just bluntly claims that `goto` is evil is an idiot. (No, I'm not calling Dijkstra an idiot. I just know the historical context of his article, something the anti-`goto` cult keeps forgetting -- and I'm being charitable here in assuming they ever actually knew.)
JUST MY correct OPINION
GOTO is just as evil as JMP in assembly. Sure you can use it badly (heck, using `break` and `continue` can make your control flow even uglier), but that doesn't mean it's *always* evil. I think GOTO should be taught as a useful but rarely needed tool.
Wayne Werner
+1  A: 

Strangest was "this must be coded in C++". Presumably I'm being hired for my expertise. If my expert opinion says another language would do the job better, then that other language should be the one used. Telling me which tool I should use is about the same as telling an automobile mechanic that he's only allowed to use metric wrenches. And only wrenches.

JUST MY correct OPINION
I don't know what project you were working on, but maybe there is an external restriction or maybe they have other people working with something other that is needed to be able to use your thing from C++.
Frank
@Frank: Part of my presumed expertise is knowing what the use case scenarios are. If there was some need to interact with others using C++ I'd either pick C++ or make some good, transparent C++ bridges if the effort was worth it. Again, having a manager with little to no coding experience make these decisions is just plain wrong. In most cases (as it was in this case) it's just a manager hearing that C++ is the latest/greatest that determined the choice of language. To the detriment of the product.
JUST MY correct OPINION
There are so many valid reasons for asking this! What if for example, the company already has support staff or/other developers who already know and support C++ applications?
corydoras
@corydoras: I say again: Part of my presumed expertise is **knowing what the use case scenarios are**. If there was some need to interact with others using C++ I'd either pick C++ or make some good, transparent C++ bridges if the effort was worth it. Again, **having a manager with little to no coding experience make these decisions is just plain wrong**. In most cases (as it was in this case) it's just a manager hearing that C++ is the latest/greatest that determined the choice of language. To the detriment of the product. Is that clearer?
JUST MY correct OPINION
+2  A: 

Our old c# coding standards required that we use huge, ugly comment blocks. You know in Code Complete where Steve McConnell gives a prime example of an ugly comment macro? That. Almost an exact match.

The worst thing about this was that c# is a language that already has good (and relatively unobtrusive) comment support.

You'd get something like this:

/// <summary>
/// Add an item to the collection
/// </summary>
/// <parameter name="item">The item to add</parameter>
/// <returns>Whether the addition succeeded</returns>
public bool Add(int item) { ... }

and it'd turn into this:

// ########################################################## //
/// <summary>
///     Add an item to the collection
/// </summary>
///     IN:  <parameter name="item">The item to add</parameter>
///     OUT: <returns>Whether the addition succeeded</returns>
// ########################################################## //

Note that StackOverflow's syntax highlighting does not do it justice, as with the default VS text scheme, the # symbol is bright green, resulting in an overpowering violation of your retinas.

I can only assume the authors were really, really fond of it from previous endeavours with C/C++. The problem was that, even if you just had a couple of auto properties, it'd take up about 50% of your screen space and add significant noise. The extra // lines also messed up R#'s refactoring support.

After we ditched the comment macro, we ended up spanking the whole codebase with a script that took us back to visual studio's default c# comment style.

Mark Simpson
Were the people who wrote your coding standard not aware of the block comment delimiters that C-style languages have?
JAB
I'm not sure that I'd classify a comment convention that inlines pseudo-HTML as "unobtrusive" -- relatively or not. Indeed I'd probably classify such a commenting convention as "fugly".
JUST MY correct OPINION
It doesn't offend my eyes or distract me when I'm reading code and it has excellent IDE support, so that's good enough for me.
Mark Simpson
+5  A: 

When using SQL Server, which has such big limits on table name length that I've never personally bumped into them, we were forced to use the naming convention from the older mainframe system, even though the new system never interacted with the mainframe database.

Because of the tiny limit on the table names, the convention was to give all the tables codenames, rather than meaningful descriptions.

So, on a system that could quite happily have had the "customer" table called "ThisIsTheCustomerTable", instead it was called "TBRC03AA". And the next table was called "TBRC03AB", and the next one called "TBRC03AC", and so on.

That made the SQL really easy to understand, especially a month after you'd written it.

Matt Gibson
+4  A: 

Our Oracle DBA's are insisting that we prepend the schema name onto table names, ie if your schema is hr_admin, your staff table would be hr_admin_staff, meaning the full name of the table in a cross schema query would be hr_admin.hr_admin_staff.

corydoras
This is a horrible convention considering the maximum length of table name in Oracle is only 32 chars.
Esko
@Esko: I thought it was even worse than that - isn't the maximum length only *30* characters?
Adam Paynter
+4  A: 

We're coding after MISRA standard. The ruleset has "MUST" and "CAN" parts, and we spent hours of discussing which rules we don't want to apply and why, when someday upper management said "We want to tell our customers we're 100% compliant. Tomorrow, we apply all."

Among the rules is one that says: No bit operations on signed data. Trying to find out what the rule is for, the explanation was presented: There is no guarantee about the bit representation of signed data. There is only 2s complement in the world, but the standard makes no guarantee!

Anyway, doesn't sound like a big thing - who wants to declare bitcoded variables as signed?

However, the holy rules checker interprets "integer promotion" as "promotion to signed" and the C standards guru says it has to be. And every bit operation does integer promotion. So instead of:

a &= ~(1 << i)

you have to write:

a = (unsigned int)(a & (unsigned int)~(unsigned int)(1 << i))

which is obviously much more readable and portable and all. Fortunately I found out that a shifted 1u stays unsigned. So you can reduce it to:

a = (unsigned int)(a & (unsigned int)~(1u << i))

Funnily, there is a rule that was not activated: Forbid using funny characters like '\' in #include. The DOS-corrupted folks won't believe that writing #include "bla/foo.h" does work even with every windows compiler and is much more portable.

Holgi
On a Swedish keyboard, entering '\' is harder than '/'. So when I'd noticed that one could write '/' instead of '\' almost everywhere I did not think twice.
Frank
+4  A: 

The first programming job I had was with a Microsoft QuickBASIC 4.5 shop. The lead developer had been working in BASIC just about forever, so most of the advanced (!) features of QuickBASIC were off-limits because they were new and he didn't understand them. So:

  • No Sub/End Sub procedures. Everything was done with GOSUB
  • We were allowed to not number lines that weren't the target of GOTO or GOSUB. But GOTO targets has to be a numeric label, not a name.
  • Targets of GOSUB were allowed to be named, but the name had to prefixed by 'S' and a four digit number. All subroutines had to have the four digit number sorted in order in the source file. So a typical routine might be S1135InitializePrinter. You'd have to go and find the right routine to get the number, there were enough that you couldn't hope to remember them all.
  • No block IF/END IF. All IFs had to have either a single GOTO or GOSUB as the conditional statement.

That was a really fun job. No, seriously.

Jules
In an ideal world they should probably not let people who have extreme fear of change into the software field, I mean for their own sanity.
John K
+5  A: 

In Java, I am currently discouraged to use boolean functions as a predicate in a test:

    if( list.isEmpty() )...

must be rewritten

    if( list.isEmpty() == true )...

and

    if( !list.isEmpty() )...

must be rewritten

    if( list.isEmpty() == false )...

because "it is clearer like that".

To me, "list.isEmpty() == true" has 2 verbs, "is" and "equals", in one phrase without a connective. I can't make it feel right.

Florian
Hmm, right "clearer". +one`if list is empty` *is* clearer than `if "list is empty" is true`.
Frank
+2  A: 

at my previous job, which I gladly quit 3 months ago:

database:

  • Table names had to be uppercase.
  • Table names had to be prefixed TBL_
  • Fields had to be prefixed: DS_ (for varchar, which made no sense) NU_ for numbers CD_ for ("bit fields") DT_ for dates
  • database fields had also to be uppercase [CD_ENABLED]
  • same with sp names [SP_INFINITY_USER_GROUPS_QRY] and database names [INFINITY]
  • did I mention sp names were actually like that? SP_ prefix, then database name SP_INFINITY_ then table name, SP_INFINITY_USER_GROUPS then what the sp was actually expected to do (QRY,UPD,DEL,INS) jesus, don't even get me started on queries that weren't just CRUD queries.
  • all text fields had to be varchar(MAX), unequivocally.
  • numbers were either int or double, even when you could have used other type.
  • "boolean" fields (bit) were int, no reason.
  • stored procedures had to be prefixed sp_productname_

asp.net / c# / javascript

  • EVERY single function had to be wrapped in try{}catch{}, so the applications wouldn't "explode" (at least that was the official reason), even when this produced things not working and not having a clue why.
  • parameters must be prefixed with p, e.g pCount, pPage
  • scope variables had to be prefixed with w (as in "working", what the hell does that even mean?)
  • statics with g, etc.
  • everything post framework 1.1 was offlimits, like you had any real uses for linq and generics anyways. (I made it a point to enforce them to let me use jquery though, I succeded at that, at least).
Nico
Just thinking out loud, could "DS" be "Dynamic Strings"? In any case, this stuff is horrible.
Esko