Best and Worst Coding Standards?
An anonymous reader writes "If you've been hired by a serious software development house, chances are one of your early familiarization tasks was to read company guidelines on coding standards and practices. You've probably been given some basic guidelines, such as gotos being off limits except in specific circumstances, or that code should be indented with tabs rather than spaces, or vice versa. Perhaps you've had some more exotic or less intuitive practices as well; maybe continue or multiple return statements were off-limits. What standards have you found worked well in practice, increasing code readability and maintainability? Which only looked good on paper?"
Sound an awful lot like coding in C... no bad coding practice needed...
Seven Days with Ubuntu Unity
Make it "cut and paste" friendly, and as small as possible.
I've worked where we were supplied a full IDE and a 17" CRT, and the coding standard forced so much white space vertically that you had to basically remember all the code.
I can't stand seeing the closing brace of an if statement sharing a line with an else, like so:
if( condition ) {
statement1;
} else {
statement2;
}
I've always found the Joint Strike Fighter's coding standards document an interesting read. It is available from Bjarne Stroustrup's website (pdf)
This sounds like a fairytale but I work for a very large IT firm which is very well known. Serious company doesn't mean good however.
In certain files (not all apparentely) all constant variables have to be declared globally. We are talking C++ here.
Think what you want, but I don't like it. The reason for the variables placements are so "that they will be easy to find".
First off, I'd suggest printing out a copy of the /. comments, and NOT read it. Burn them, it's a great symbolic gesture.
is classic one - brilliant example of really harmful coding standard. Especially after Years of refactoring, where wParam doesn't mean WORD anymore...
Also found I prefix in .NET really bad pracitce for marking interfaces like ICollection, what about when You decide turn interface to abstract class?..
Generally embedding some semantic value into the syntactic is IMHO really bad practice.
Well, also used to work in company which decided to use Capiltalized names in Java, so instead fo getFoo, they decided that is much cleaner to have GetFoo. Of course ta the same time, the company had to accept that half of the Java frameworks, following JCS didn't worked for them...
lima
My new standard comes from a 1950's comp sci book.
"Programs consists of input, output, processing and storage."
Lose focus of that and the project will be late, over budget and most likely broken in ways no one will understand for years.
One good coding standard is:
The first line of foo.cpp has to look like:
#include "foo.h"
It ensures that foo.h is independent of other header files.
If you are using your computer right, it does not only enable you to do things, it does the boring things for you, automatically.
Checkstyle is one of the tools in a company toolkit that is often overlooked but in fact VERY handy. It enables you to define a ruleset for your source code, finding stuff which is incompatible with the coding practice in your company/team/project/whatever. Moreover, you can stick it into Eclipse using the free Eclipse-CS plugin, so it will automagically mark the places which need to be change. Last but not least, you can put Checkstyle as an Ant task in your building environment (and in your continous integration toolkit) so commited code that does not conform certain standards does not build.
As for the rules themselves, we've found these to be the most successful:
Of course, we let developers to add suppresions for the 1% of false positives. In fact, there are very few suppresion rules set.
Build a tool even an idiot can use and only an idiot will want to use it. -S.O.B.
the one that follows the code I write. Every other standard is crap.
Without developer buy-in, whatever coding standards you come up with will be useless. IOW, ask your developers to create the standard together.
Je ne parle pas francais.
Take a look at the JSF C++ coding standards - www.research.att.com/~bs/JSF-AV-rules.pdf - Stroustrup had a hand in them and our internal standards use them as a base.
One of my friends worked at a place where you'd have to insert whitespace to place certain elements (variables, evals, etc.) to begin at a specific col in the code within every line; in addition to standard indentation of the line. At one level, I see the concept, but seriously - highlighting and search is made to solve the same problem there.
He left that job quickly.
Returned Peace Corps IT Volunteer
Hungarian notation. Ugly.
At my first industry job (internship) I quickly realized their coding standards were very different from mine. So I spent the first 2 hours after lunch on day 1 with GNU Indent, working up a script that would convert my code into the company's coding standard for indentation.
Let the tools do the work for you. Just don't forget to run 'indent' before you check in your code.
General Relativity: Space-time tells matter where to go; Matter tells space-time what shape to be.
The worst example I ever saw was some IBM Federal Systems code written in the 1970s -- they enforced the "one page module" rule using nested includes -- NINE LEVELS OF NESTED INCLUDES!! Of course, this was coded in a FORTRAN-like MIL-SPEC language with eight character filenames, so you can guess how hard it was to find a particular module. It was at least three levels down to find the first page of global variable declarations.
I worked for a company that was destroyed by a bad coding standard.
This was a small company, that, back in '96, was awarded the contract for a POS application for a regional store chain, with back-office servers that would be updated nightly by modem.
The guys who ran the company weren't programmers (though one of them knew enough to be dangerous); they were technical salesmen. They were also big fans of Microsoft, with "MVP" plaques on the walls, and every employee except me having Microsoft certs.
I worked for them part-time while also working for another company. I advocated Unix (mostly BSDI and SunOS at the time), and always argued with them about why Unix was better (technical superiority vs. potential for big profits).
When their big project was well underway, they brought me in to do the communications part of it, where the POS terminals would contact one of several servers by modem each night ("why not just ethernet them together, get a dialup PPP connection, and use IP? the interface is so much more reliable..." Request denied).
The app was Visual Basic, with third-party "custom controls" for things like talking to modems. My part went fairly smoothly, and I was eventually asked to help out with the main application, which was suffering from unexplained crashes. When I looked at the code, I found something... strange.
For error handling, they had elected to use a program called "VB Rig" (the name came from the rigging used on sailing ships, which prevents a sailor from falling to his death. Sometimes.) What this program did was to examine the source code, and then add error handling boilerplate at the start and end of each and every function. It inserted the exact same error handling code into every function.
Because the error handler had to be all purpose, it was about 20 lines of code per function - sometimes much larger than the regular part of the function. And, worse, because it was the same for every function, and it made use of the same variable names, that meant either every variable had to be global, or you'd have to declare the ten or so standard variable names at the start of every function (they opted for the "everything is global" approach).
Which led to things like this (forgive the syntax errors, it's been years since I've touched VB):
On Error goto my_data_file_read_function_VBRIG_TRAP
open MyDataFile for writing ...
goto my_data_file_read_function_VBRIG_CLEANUP
my_data_file_read_function_VBRIG_TRAP:
on error 101 'Permission Denied
delete MyDataFile
resume
on error 102 'File Not Found
MessageBox 'Cannot read ' + MyConfigFile
resume
my_data_file_read_function_VBRIG_CLEANUP:
blah blah
my_data_file_read_function = SUCCESS ' return
As you see, the error handling code - which had to be exactly the same for every function - made use of global variables (names like DataFile1, MyFile1, UserName, etc.) to figure out what to do for each error. That meant, that if there was any possibility you might have a "File Not Found", you had to expect the filename where that might happen to be in a particular global variable - say, MyFile1 - and hope that the calling function wasn't using that name too, for the same reasons.
Naturally, files were being created and deleted at random, and the programmers often spent hours on the phone with the customer trying to figure out why the Access database had disappeared *again*.
I asked if we could just write the error handling by hand, and use appropriate local variables; or take the standard VBRig error handling and trim out the lines that weren't relevant for a particular function (as subsequent VBRig runs wouldn't touch its code region if it saw that it had been customized).
Request Denied. "This is our coding standard. We carefully reviewed the options before making the decision to use t
.
Coding guidelines are typically justified because, as it goes, most of the time is spent fixing bugs in existing code than writing new code. The guidelines are needed because it helps others to come up to speed quickly while they try to figure out the code in which they have to fix the bug(s).
I think that is the wrong focus, as it tends to reinforce incorrect behavior, i.e., the writing of buggy code.
Coding guidelines should focus instead on the techniques that help reduce the number of bugs in code. How is that done? It takes someone (typically a senior person) looking at the the bugs that have been found in the code, categorizing their cause, devising a way to prevent those bugs from occurring, then putting that into the guidelines.
Keep the focus of the guidelines where it should be: to increase the quality of the software.
On the strange side is the omission of vowels on functions and varible names to save text space (it's not required, but should be consistent for similarily names objects). It sounds weird, but is still quite readable.
Guidelines and standards[1] are not rules. Rules are much harder to write because they have to anticipate every possible eventuality. The purpose of guidelines is to make people think good and hard before breaking them[2].
Never did understand the fuss about GOTO... you need them everywhere in machine code, FORTRAN and (original) BASIC because that's the way the language works. Its perfectly logical to use them for exception handling in C or Pascal (and it was childish of "standard" Pascal to implement them in a deliberately perverse[3] way) and if you are using a language with decent structures and exception handling, the need just doesn't arise.
[1] that's "standards" in the sense implied here rather than the W3C sense. God! I almost said ISO there, have to break that habit...!
[2] Actually, I think the original Pratchett quote I've pinched was talking about rules but lets not be too subversive...
[3] In "standard" Pascal you had to use numerical labels which had to be declared in advance...
In a survey of 100 programmers, 111111 thought that duck-typing was a good idea.
If you're going to have standards, they need to be enforced. the best way to do that is to have any style elements created by software, so the coders can write in their own way, but the house style is what's delivered to the client. This includes file headers, disclaimers and copyright statements.
Of course the one place where coding standards never seem to apply is after the code is written, when the patches and bug-fixes are added.
politicians are like babies' nappies: they should both be changed regularly and for the same reasons
For anyone coding C or C++, I strongly recommend CERT's secure coding standards:
https://www.securecoding.cert.org/confluence/display/seccode/CERT+Secure+Coding+Standards
In theory, a good idea. Code reviews are a good thing. Not releasing unreviewed code (at least for general, not testing use) is a good idea. The company even had a system set up for requesting and tracking pending code reviews.
In practice, however, nobody gets around to reviewing anyone else's code for weeks or months after the request is made. Meanwhile, if you're a prolific coder, you've wound up with patches building on patches of patches that are built on other patches.
When someone finally gets around to the review, they either don't review them in the order they need to be committed (approving things that can't be committed until something else is reviewed), or they have you change some things in the earlier code that causes a cascade of having to merge changes, regenerate patches for all those pending reviews, resubmit them for review (particularly fun if they've already approved something that had to change), etc.
Proper approach: use development branches, review requests made in parallel with checkins, changes that come up in review open new cases/tasks, development branch collapsed once all the pertinent reviews are approved.
Not to start a flame war here, but goto's are used at some large companies. Their usage is strictly for error handling, like if (error) goto exit; Usualy same companies use a single return at the end of the function. I've seen this later part at more than one company being used.
One benefit in using "goto exit", is that compiler/optimizer recognizes labels like exit, errorExit, etc. and considers them to be less likely to happen, thus allowing for more optimal code execution.
I'm not familiar with exceptions in C/C++ well, but from what I've heard they're more expensive than a simple goto. For performance sensitive code, you cannot afford this.
1. KISS - Keep It Simple Stupid, don't be unnecessarily complex.
2. DRY - Don't Repeat Yourself, if two or three places perform essentially the same actions then that should be one function/method with the differences added and commented.
3. Make it easily readable. This means simple yet meaningful variable names, comments where anything non-obvious is done and appropriate use of encapsulation/isolation (no methods/functions that are too long, and none with only one or two actual lines of logic).
Anything else can fixed with a code beautifier/pretty printer/reasonable IDE or editor.
-- More Smoke! The mirrors aren't working!!!
K&R style is all you ever really need.
The only coding standards that I think work are ones that are developed over time by coders and their managers together to solve specific problems.
must... stay... awake...
I've come across, been subject to, and written many coding standards during my career and have come to the conclusion that coding standards are, for the most part, useless.
It is much better to let coders program to whatever style they are most comfortable with. Forcing specific bracing and indentation styles just leads to ill-will from most coders and creates a bureaucratic overhead that is more more trouble than it is worth. As long as the style is consistent within a single file, most programmers will have no trouble following it and have no trouble maintaining the code.
The only standard I think is worthwhile, when coding API libraries and such, is a naming standard. For example, a coder should not have to guess whether the method to get a property value is getProperty() or property_get() or propertyValueOf() or whatever. I don't care what the naming standard is, as long as it is consistent across the API.
Life is like a web application. Sometime you need cookies just to get by.
Honestly, I can't think of a single project I've worked on where coding standards made a bit of difference. Poor programmers will write lame code that complies with the coding standards, while great programmers will write great code that complies with the coding standards. Pissed-off, alienated programmers can obnoxiously comply with coding standards by writing incomprehensible and fragile code.
I personally like to write software that someone, somewhere, will actually use. How do coding standards actually help that problem?
My own experience has been that detailed coding standards tend to correlate with projects and products that go wildly out of control. My hypothesis on why that happens is that people involved in such projects all subconsciously know that and are desperately trying to control at least some aspect of the product development process. (one of my favorite's was a brief stint at a large, heartless company that makes large aircraft in a somewhat rainy part of America -- "all C functions must return a value, and all function return values must be checked". 'nuff said)
Each language or environments have their own features, and require different standards. One of the big things is that hopping from one project/company to the other should be intuitive (something thats basically forfeited in environments such as C++, and accepted as to not be possible, more or less) When the language is mainly controled or orchestrated by a single entity (Sun for Java, Microsoft for .NET, etc), people should set aside their own opinion and stick to the main guidelines (and complete them for areas where the main design guidelines do not cover).
So for example, in .NET, stick FxCop or Code Analysis on, disable the rules that aren't relevant to your company (ie: localization rules on an app that doesn't require them), and stick to that. C++/VB6/Java/Smalltalk conventions have no place in there, so leave em out.
Same holds true for any other environment. Don't use VB6 conventions in Java/C++ (I know the thought alone seems mind boggling, but I've seen it countless of times....ugh!), and so on.
The biggest issue with conventions is just that: people take conventions that are specific to one language/environment, and don't realise that they are, so they port them everywhere else, so you have a program in language X that literally looks like if it was written in language Y (and takes twice as much code, is twice as buggy, is half as readable...)
Buy a copy of Triemax Jalopy, create a policy, then hook it up to your source code repository so that when developers check in their code, it automatically formats it.
Problem solved. Everyone's code looks the same.
Some coding standards can be useful to enforce consistency in variable naming conventions, for instance. But if the document is lengthy and burdensome (with version history meticulously displayed at the beginning of the MS Word doc), and is meant to be kept handy during code reviews, that's often a sign that whoever prepared it is overmatched for the senior-level job they were originally assigned to. I've noticed this at several companies where I've worked.
Consider letting the coding standards writer go during the next round of layoffs.
multiple return statements were off-limits
Despite the fact that it's not part of the coding standard where I work, I have a few coworkers who take this to the extreme. They surround every single function they write with: ... } while(0);
do{
And then, inside the "do" block, they just put "break" in any place where they would have otherwise put "return." It drives me insane; they insist that having a single exit point from your function makes it easier to debug, but I just don't get it. I've never even seen them use gdb, anyway, so I think that abusing "printf" is their idea of "debugging"...
One thing in our coding standard that I do like is that all variables that store units must have a unit specification at the end of their name -- in other words, all frequencies might have "Hz" or "MHz", distances might have "m" or "mm", times have "sec" or "msec", and so on. This is really helpful in my field -- it's not uncommon for me to open up a file that I've never looked at before and need to make modifications to it, and if the units everything things are stored in weren't immediately obvious, I'd have to go track down somebody and ask them. The annoying thing here is when people decide not to follow this standard because they think it should be obvious...
Karma: Terrifying (mostly affected by atrocities you've committed)
I work for a major software vendor. The particular group I work in wrote the application framework for a suite of apps. Our code is mostly quite nice. There were about 20 people working on it during development and there are a few pieces that are crap, but for the most part, it's quite well designed and written.
Now, there are other groups that use this framework. One group in particular, has pretty much the same standards that our group does. The difference is, however, that their manager never had them do code reviews and so people pretty much ignored the standards. I've now been tasked with working with that group and their code is a complete nightmare. For example, a single form class with something like 16 tab pages (spread among 3 or 4 tab controls), over 200 controls, and over 9000 lines of spaghetti code.
Had this group done code reviews, this class never would have passed, and it wouldn't be such a nightmare to deal with. At this point, we're already shipping the second version, so a complete rewrite of the various nightmare components of this app are out of the question, which is too bad because it's going to be a nightmare to maintain, especially when the guy who wrote it leaves.
I've always hated doing code reviews, but this experience has made it abundantly clear to me how important they are for minimizing the damage a single clueless programmer can get away with.
FYI, here's what it's like at Google: Google C++ Style Guide
A lot of coding standards are mostly personal preference, like indenting x spaces. Here are some for C++ that I think make your code less error prone.
* Allocate resources in constructors, deallocate them in destructors.
* Put objects on the stack, whenever possible.
* If it does not make sense to copy or assign an object, then disable the copy constructor and assignment operator by declaring them, and not implementing them.
* Declare and initialize objects as close as possible to where they are used.
I would highly recommend this article http://www.freevbcode.com/ShowCode.Asp?ID=2547/ enough for fun. but probably some people are already doing some of them in their code?
I've never been convinced by any hard-and-fast coding stylistics. Sure, it's possible to write good code and bad code, readable code and unreadable code, but beauty is very much in the eye of the beholder, and, also, it depends a lot what you are trying to do. Insisting on one inflexible set of stylistics works about as well as telling people never ever to split infinitives or never ever to use the word 'said'.
Last night I came across this in the documentation for CPAN's Net::Server (you probably guessed from the above that I'm not a Pascal programmer):
You may get and set properties in two ways. The suggested way is to access properties directly via
my $val = $self->{server}->{key1};
Accessing the properties directly will speed the server process - though some would deem this as bad style. A second way has been provided for object oriented types who believe in methods. The second way consists of the following methods:
my $val = $self->get_property( 'key1' );
my $self->set_property( key1 => 'val1');
This struck me as remarkably sensible - the author of the module puts his prejudices on the table, but tells you how to do it a different way if you like. (And, personally, I prefer the first example, because it's just as clear, faster, and I've never managed to take OOP in perl entirely seriously - a problem that Larry Wall appears to have too.)
You judge good style in any particular case by looking at the overall work, not by nit-picking about the punctuation in isolation.
Virtually serving coffee
There are tons of coding standards, but the fact is when you writing code, it becomes a real pain to follow everything to the dot. I sometimes feel that just three things are followed(in no particular order, all are equally important), that enough.
1. Write simple code, no cryptic code(Though sometimes for optimised code this might be not all that simple)
2. Write small functions. Anything more than 50 lines is better moved to a function(Making functions inline makes sense sometimes)
3. Give variables and function better, self explanatory names than i, j, temp,test etc. Give specific names(like rowCounter, loopIterator etc) , instead of generic names(like i, Counter, tempNode).
If it's assembler then write pseudo ADA comments which bear no resemblance whatsoever to the badly commented code following - Bonus points if the pseudo code itself has bugs...
If it's Delphi code make all units UNITx, all forms FORMx and all variables equally inanely named - if it's good enough for most Delphi books then obviously it's the right way to do things
Avoid function prototypes - if it was good enough for Brian and Dennis it's good enough for anyone
Overload operators in surprising and pleasing ways, preferably so that "-" does bitwise set inclusion
Use macros extensively (without ()() because everyone knows only losers need them).
Mix tabs and spaces indiscriminately
Pick at least *two* styles for braces - Bonus points for gratuitously adding them where they aren't needed - (to really make the reader happy use the "{" on next line style here)(extra points if you are mixing tabs and spaces)
Use if (1==x) , (x==1) and just plain old if (foo) randomly to add variety
Write big huge case (switch) statements spanning 5 pages because no one would possibly understand dispatch tables
Seriously though, if you're programming anywhere you're expected to conform to the local customs, wacky and out of it or not. It's part of the adaptability expected of a programmer...
Andy
Forget this pointless stuff about tabs and spacing, I've seen some really brain-dead policies.
1) Source Control Substitute
At one shop, there were designers who edited XML + image files (kinda like web pages, but not quite). There was a compiler that built this all into a single executable. They were not permitted to edit the source directly, and had to work on copies. And those copies must be on the network instead of their local drive. And source control was not allowed.
So instead of people having local copies and then committing their work, everyone made a duplicate copy on the network for each thing they did. It took hours to make the copies, and the compile times went from a few minutes to 45 minutes. Plus, the network drive kept running out of space due to all the gzillions of copies of everything.
2) Making the "minimal" change required
I worked for a US government contractor and they wanted each change to have the minimal impact on the system that was possible. So, basically nobody ever removed code, only added. One time I encountered a huge nested if statement that spanned hundreds of lines. Upon looking at the cases, I noticed that many of them were the same. Like:
if (a)
if (b)
do x
else
do y
else
if (b)
do x
else
do x
which can, of course, be simplified to:
if (a and not b) do y else do x
This was because people had to make the MINIMAL change required each time a change was made. And removing a level of the if statements was more lines of code modified than just changing "do y" to "do x"
Imagine this, but with dozens of cases spanning hundreds of lines. I spent almost a day to build a chart listing what each combination of variables did, and finally chopped hundreds of lines of code to about 10 lines. Turns out that after years of changes, most of the cases now did the same thing.
The MISRA software development guidelines for C can make a lot of sense in embedded, real-time or safety-critical systems, and can also be applicable outside of that application domain.
On the whole though.. one thing that tends to be lacking in coding standards is an underlying reason behind many rules - it's hard for developers to judge the applicability of an exception if they don't know why the standard was introduced - common error? Past internal experience?
And we have files that run 8k lines, they're unintelligible and almost impossible to maintain.
As far as formatting goes, I believe in letting each developer do it however they like. Things like braces on the same line, or on the next line just don't matter that much in a world of automatic code formatting utilities.
I just wish there was a way to view code in your preferred style, but not actually modify it.
Good (personal preference, rather):
- braces on separate lines
- white space after parenthesis
- white space between operators
- white space after commas
- white space between ideas
if( something == something_else )
{
arg1 = argx + argn;
idea1( arg1, arg2, arg3 );
argz = argy + argg;
idea2( argz );
}
My reasoning for this is legibility. I find that those that don't do this tend to write "wall-o-text" code, e.g.
if(something==something_else){
arg1=argx+argn;
idea1(arg1,arg2,arg3);
argz=argy+argg;
idea2(argz);
}
I just think the white space makes the code easier to read, especially in the absence of comments or function/variable naming standards. Think of the ideas like paragraphs.
Another two good ones are all caps on CONSTANTS and constants on the left of a comparison, e.g. CONSTANT == var, to catch any assignment typos.
Bad (or silly):
- line length restrictions
I've just never found this one useful. Usually, the reason for it is for printing, more so for older printers that would truncate past 80 characters.
- endless( arg1 ).calls( arg2 ).strung( arg3 ).together( arg4 ).off( arg5 ).a( arg6 ).variable();
I'm on the fence on this one. Sure, I see the value of less lines, but wow it is hard to get the idea out, especially in the absence of comments.
I think these questions on slashdot are like hoping your 1000 monkeys will eventually create Shakespeare. I hope you like reading.....
-fragbait
Some programmers think they should be able to do anything they want.
That might be OK if you live in your parents' basement and code for yourself, but in the real world it's a bad (and selfish) idea.
Strict adherence to a standard is helpful in code review and in cases where a component is taken over by a new maintainer.
This is always important, but it's particularly important in a genuinely open, community-driven project.
The Drupal project is an example. It has a coding standard derived from the PEAR project that applies to any code submitted for inclusion in the core.
Contrib authors are encouraged, but not required, to follow it. The good ones do.
The Drupal Coder module does a very good job of nagging at you until you get the formatting right, and also helps with code migration and updating when the API changes. And it finds some common bonehead mistakes that can create security issues.
Adhering to a standard doesn't have to be painful. Using a properly configured text editor helps. There is good support for Drupal standards and conventions in OpenKomodo and the commercial Komodo IDE, as well as some other editors.
The 3 year olds were at test at Stephens College (Columbia Mo) in their preschool education classes around 1986 or so. There are published papers but I've got no idea where to find them to cite them.
These 3 year olds were given a 10 minute time out and a grape juicebox. During the timeout, the 3 year olds developed time travel, went back, deleted the test and grape juiceboxes.
The only thing new in this world is the history that you don't know.[Harry Truman]
If you are using your computer right, it does not only enable you to do things, it does the boring things for you, automatically.
Exactly. Use the tools.
In the .net world, check out
fxCop: http://msdn.microsoft.com/en-us/library/bb429476(vs.80).aspx
StyleCop: http://code.msdn.microsoft.com/sourceanalysis
These can both be used to prevent code building if it doesn't meet standards. Sadly, the first task for me is usually to turn on "warnings as errors" and get the code up to that minimal standard.
Also check out Resharper: http://www.jetbrains.com/resharper/
for flagging some code problems.
The problem with code standards is that your best coders are probably using a standard already; and the while the worst can be dragged onto a standard, they will write bad code even with it.
My Karma: ran over your Dogma
StrawberryFrog
This is particularly true of Java and C#, where language/platform creators have established a standard themselves. Though I've noticed that Sun's Java coding guidelines seem to be more closely followed than Microsoft's C# guidelines, particularly with regard to the placing of curly braces (but then again, Microsoft themselves don't follow their naming and bracing guidelines, as anyone who looked at the .NET source code quickly found out).
For C++, this is trickier - you have several indentation/bracing standards, and also camelCasing/PascalCasing/separate_with_underscores. Sometimes it's a no-brainer - if you mostly use Qt, then just follow its style. But for projects that use many different third-party libraries (or the opposite - when few/no third-party code is used), you'll have to pick something. Personally, I've found Java-style naming to be the most convenient (PascalCasing for class names, camelCasing for variables and functions, ALL_CAPS_WITH_UNDERSCORES for constants), though I still prefer ANSI C indentation and bracing (braces on separate lines, not indented to the level of their content).
One of my pet peeves is people prefixing Interface names it 'I'. This exposes an implementation detail to the user of the Object that it should not and makes it difficult to refactor.
Another horrendous one is hungarian notation, this should be explicitly banned and punished.
The difference between Canada and the USA is that in Canada healthcare is a right and gun ownership is a privilege.
We found that it doesn't really help to enforce a *formatting* style on developers because everyone has their own. The only thing you really should be enforcing is tabs vs spaces (and it should be spaces) because mixing the two can produce some really ugly results.
We have a much better rate of return running tools like JSLint or PMD to catch issues that are syntactically valid but will be sure to cause problems down the line
I believe the worst standards are the ones that limit the languages to make them work as another language. Typically it's C++, or even Java, transformed into C. "No operator overloading, no virtual methods, no multiple inheritance, no function/method overloading, no const, no 'non-standard for' constructs, no return statements (other than at a function's end), no function call inside parenthesis (as an operator, or as an if/while test), no class constructors/destructors, no STL/Boost/whatever, no long (+15 chars) identifier names".
Amazingly, even Google (which you would expect to only hire high-level developers) has some of these guidelines for C++.
The best guideline is no guideline at all. Take your potential guideline, and present the rationale to the developers, with colorful examples to show what problems the guidelines are trying to avoid. Show them what "bad code" looks like and as soon as they realize they will naturally avoid it. If they argue against a specific rule it means that it's either a silly one (and should be discarded) or the guy is too dense to understand the problem (which means he needs more training, like maintaining a really awful code base).
In a way, the languages, tools, and libraries prescribed (if any), also constitute a sort of coding practice, in the sense that they impose limits on how you can structure your code.
- The language you work with gives you certain language constructs. These constructs vary per language, and determine how you must express things and what abstractions are available to you. This has a huge impact on the structure of your code.
- Most tools like to structure and format your code a certain way, particularly when the tool generates the code. This is usually a great boon, because it will make it easy for programmers to adhere to the same coding standard and hard for them to deviate. Of course, if what you want is not what the tool wants, the tool starts getting in the way.
- The libraries you work with determine the APIs available to you. This also has a strong influence on the structure of your code. It also interacts with the language constructs available to you, as they may or may not make it easy to build an API you like to work with on top of the API that a library exposes.
Abstraction is particularly important. If a language offers powerful enough abstractions, you can structure your program so that it is easy for humans to understand what it does, and have the compiler translate it to whatever the libraries make available to you. Better abstractions also make your code more reusable.
As an example, in C, strings are character arrays. Arrays in C don't have a size associated with them. The end of a string is indicated by a character with value 0. Furthermore, the type of an array of characters is actually the same as a pointer to a character. C also doesn't have automatic memory management. Suppose now that you wanted to concatenate two strings. There are various ways to do so, but the most obvious one is the strcat function:
This function appends src to dest and returns dest (a pointer to the concatenated string).
That is, provided there was actually enough space in dest to hold the combined contents of dest and src, and the terminating NUL. If there wasn't, the function overwrites whatever came after dest, which will usually lead to your program crashing or executing code supplied by a cracker attacking your program.
The correct way to use strcat, then, is something like:
But wait! That's not all! Since the type of an array is actually a pointer, and pointers are allowed to be NULL in C, first and second in the above could actually be NULL. If either one of them is, the program will crash. So we need to add extra code to check for that ...
All those many things to remember to concatenate two strings. It doesn't have to be that way. In OCaml, for example, a string is a string, not a pointer to a character, and never null. You don't have to worry about allocating a large enough block of memory, because memory will be allocated as needed, and reclaimed when no longer reachable. As it happens, OCaml also has an operator that concatenates strings. That is besides the point here, but I had to tell you that to explain what the code looks like in OCaml. Namely:
Not only is it much shorter than the C code, it's also easier to understand what it does, and more robust.
I think this sort of thing matters a lot more than how you format or indent your code, and pretty much everything else that normally falls under the nomer of "coding standards".
Please correct me if I got my facts wrong.
If you are working for a compagny which pretends engineering software and which starts by giving you a coding rules guide of one hundred pages long which speaks only of indenting and whether or not to uppercase function names regarding their scoope or how to format function name prefixes regarding the supposed module they belong to, then RUN AWAY ! (1)
There are plenty of utilities which are able to automatically do all that typo job for you.
Do not confuse coding rules and presentation style, coding rules focus on adding formal information about symbols or instruction blocks which are not already implied by the semantic of the used programming languange.
For instance, in C, if you use macros which are a substitute for inline functions, then it is good to provide a prototype for the implicit function and a syntactic tag which explicit the way the macro will be used within the macro definition.
This way, a home-made static code analyser is less likely to get confused by macro-which-looks-like-functions.
Once such formal information is put whithin your code, any serious text editor will be able to reformat and to present it the way you like most.
And such way of presenting code can be different regarding that you are currently writting it or that you are an integrator who have to merge two versions of a file or that you are reviewing someting written by one of your coworker or again that you are rewriting a piece of code you wrote some monthes ago, etc.
Continuing on C, what kind of macros will you allow to be used, only constant definitions? Inline functions replacement?
More complicated: if you use critical sections over data or code, what kind of information do you add to let a tool verify that you do not jump out of your section without realising it?
Presentation style can be usefull, but coding rules are about making a link with the design and test plan constraints and requirements.
If, in a software compagny, people debate on presentation indents and typo rather than on formatting tools and static analysers, well, they just don't get it, or more precisely they lack the competence and the talent to formalize the relatio n between the information they would like to be presented within the code and the semantic of this information. In this case, you will see presentation style changing regarding who is in charge of deciding it, regarding the current coding fashion of the moment, while the base coders will still being complaining of doing the same thing year after year, hitting the same kind of problems on the same kind of code, and that they expect code reviewing to be about the semantic of their code and not about typo.
(1) well, I guess it depends on how much you are paid, after all ;)
Now why would anybody do this? I've always assumed code like this was basically what inexperienced people would use:
Why not just return immediately if any basic conditions or assumptions are not met and prevent that completely unnecessary indentation? The only advantage I can see is that you could miss the return statement when reading the code.
:/- spoon(_).
That's easy... object oriented
Linus Torvald Linux Kernel coding style http://lxr.linux.no/linux/Documentation/CodingStyle
Bjarne Stroustrup C++ Style and Technique FAQ (Trivia and style section) http://www.research.att.com/~bs/bs_faq2.html
The most of so called "Hungarian notations"(including the ones previously recommended by Microsoft) is the wrong interpretation of the original ones. No wonder that Torvald , Stroustrup, Sutter and Alexandrescu don't recommend them. However, the original notation are quit reasonable and can be found here http://msdn.microsoft.com/en-us/library/aa260976(VS.60).aspx
Finally, there is the good book C++ Coding Standards: 101 Rules, Guidelines, and Best Practices By Herb Sutter, Andrei Alexandrescu
The best advice from this book " Don't sweat the small stuff. (Or: Know what not to standardize.)". For example " Don't specify how much to indent, but do indent to show structure" etc.
I've tagged the article bikeshed. It's one of those subjects everyone can have an opinion of that matters little. IMHO.
Key points:
There is no 'one size fits all'. It depends on the language, the corporate culture, and even the kind of app you might be writing.
A coding standard is necessary for teams of any reasonable size - even though people will complain about them, chances are if the team is that large, the code will be maintained for 'generations' of developers. You need to optimize for the poor sod a year from now who has to understand what this code is doing, not optimize for the guy today who wants to be clever.
The coding standard should not be externally imposed by an organization that doesn't have to live with the decisions.
The coding standard should evolve over time. Languages change - for example most coding standards I've seen for Java don't say 'boo' about the syntax changes introduced with generics or annotations.
Here's how you achieve that:
1) Start with a blank whiteboard
2) get the team that will be writing the code together
3) list everything you agree upon, get that out of the way
4) list stuff you *mostly* agree on, and get dissenters on board, even if only for a 'trial' period.
5) Every few weeks (perhaps corresponding with your retrospective at the end of an iteration), review what is working, what isn't and make changes.
This way, the standards will evolve with the needs of the team, and people who dissent only have a few weeks before they get to try to sway people again, and learn to give up if the idea doesn't take hold.
Respect people's pain when making these decisions. You might have strong opinions that conflict with someone else on your team - in the long run, it doesn't matter who is 'right', but the poor guy who is constantly trying to pull fixes up into a release branch might really be pissed off when the 'brace placement churn' causes him issues. He might not care *where* they are, just that they don't change every week.
Issues that there are no good answers to:
1) When you change your coding conventions, what heppens to all the code that follows the older conventions?
2) If you are doing a lot with branching and merging in a version control tool, churning of the coding standard can create 'false diffs'. You'll want to minimize these while evolving the standard.
So, don't try to come up with the perfect coding convention document, try to come up with the perfect mechanism by which your team can develop and evolve the conventions they need.
Having to skim through thousands lines of html to find some embedded control statement.
Or you could, you know, use an editor that does proper syntax highlighting (usually switches background color between HTML, Javascript or PHP) and has a proper search function.
As a bonus, those editor are usually capable to reformat the code spacing and make it compliant with standard rules used in the code repository, so you'll have your "else" where *you* like it, and the editor will put it back in place for the others.
"Sufficiently advanced satire is indistinguishable from reality." - [Tips: 1DrYakQDKCQ6y52z6QbnkxHXAocMZJE61o ]
Our company provides, among other things, software engineering support to customers who themselves develop commercial products. In such cases we have to make our code as indistinguishable as possible from their own in-house code. One customer has a naming convention descended in ages past from the old Hungarian notation which makes for code that reads horribly. As example:
pstFoo->fBar -- a pointer to a float (or double) 'Bar' in structure 'Foo', or
dCALCOEFF -- a #define or a macro, (certainly not a double as the rest of their naming scheme might imply, and
fnSomething() -- a function (like the parens don't give it away)
Our philosophy is "name & format for maximum readability and let the compiler catch variable typing errors," which works well if you clean the code until it builds without warnings. These folks routinely build with dozens and dozens of "normal" warnings. Their entire "coding standard" is a case study in what not to do.
http://en.wikipedia.org/wiki/Indent_style
http://en.wikipedia.org/wiki/GNU_Coding_Standards
I like the BSD KNF style.
I work in a highly-regulated industry. We use the MISRA standard for C, and use an automated code analysis tool to find rule violations. This would probably be overkill for non-safety-critical applications, but might give you some ideas.
The test subjects could all count and they were subjected to an adding program that the all did very well with... until I pointed out that I though they were seeing 4+3 as find the 4 and count 1,2,,3 on the next keys. The pattern matching was done with a wide range of other subject matter including having them find quotes in Shakespearean plays. It appeared to me that they could judge how long a boring speech was and point out a proportionally long paragraph in a book if it was all on one page.
Just having a set of standards in the first place is way more important than trying to decide which one is better.
In fact, trying to get developers to agree on coding standards is an exercise in futility. You're better off having your development lead / architect make these decisions.
.. asking a bunch of passionate amateurs, I usually go take the advice of someone I know has years of experience in the field and hopefully has editors that I can trust.
http://www.amazon.com/Coding-Standards-Guidelines-Practices-Depth/dp/0321113586
If both Herb and Andrei got it wrong, then I who am I to try and get it right?
I suppose you didn't specify which language you are using. So it's possible that nothing in this book (or a similar book) will be valuable to you. However, I highly doubt that. Much of the advice is valuable cross-language. My advice would be to not worry about the small things that just annoy the programmers and make sure your standard covers the big, important ones.
There are 10 types of people in the world. Those that understand this sig, and those that beat up people who do.
The maximum length of a line is around 100 characters (+ or - 5). Keeps code readable in many editors and shuns excessively complex statements.
Somebody earlier wrote about having subroutines which didn't fit on the screen. I agree, which is why all developers in our company use monitors which are tilted 90 degrees to fit more lines per screen. (Samsung makes some sweet high refresh models which swivel with no special mounts or anything)
However breaking things into small subroutines isn't not always practical, you end up with far too many subroutines which are "dubious" in purpose and it *can* directly conflict with another writer who talked about good names for subroutines. One subroutine per page also conflicts with the black-box idea that each routine should *always* validate it's own data. Good validation can *and should* often take more than a page on it's own.
To solve these seemingly contradictory mandates we've adopted a process of adding "sanity" lines which are large inline comment blocks which segment various parts of a subroutine.
e.g.
################ SANITY ##################
## at this point the following is true:
##
## 1. all user supplied data has been validated.
## 2. the fuzzinator is true or $err is set.
## 3. all the arrays are initialized.
##
## now lets go for a ride.
##
now .. it means that if i want to add validation data I put it ABOVE the sanity line, and below the sanity line I can implicitly trust any data.
oh yeah, for this to work and only ONE return allowed per subroutine unless it is above the first sanity line... but in general every routine MUST exit at the bottom. so you end up with lots of
if (not $err) { // do something ..
if ($ohshit) { $err++ };
}
it's kind of complicated to explain this stuff, and I'll freely admit new guys hate it for the first 3 months. But once they get the hang of it then we've found it also reduces our error rate and the overall cost of lifecycle maintenance substantially.
Last note: comments should *always* be fun, they can tell a story (this is a pro technique), they should (and routinely do) include swear words. Anything which would be non-obvious to a n00b c0der should be commented. All regular expressions should indicate WHY they exist (not what they are doing)
BAD EXAMPLE:
$foo =~ s/[^a-Z0-9]+//g; # strip non-alphanum chars
GOOD EXAMPLE:
$foo =~ s/[^a-Z0-9]+//g; # username must contain only alpha-num
Finally -- and this is the most important: as I said earlier make sure your comments should be written to be fun for the reader: drop easter eggs, riddles, haikus, hide n' seek, baby games, user dialog (short plays), ren & stimpy dialog (stimpy you idiot!), pinky & brain dialog (what are we gonna do tonight brain), are all some of my favorites. Fun comments makes the next guy/gal much more likely to actually READ them --- and means their less likely to screw up the code which will result in more work for all of us. It also entertains managers who want to look over our shoulder and makes the qa team more likely to go look in the code so they can develop better test cases.
For one thing, they is grammatically plural.
--MarkusQ
... as the process and the explanation. Every rule in the guidelines should be there for a reason, and the reason should be explained so that it's clear (and straightforward to justify) when you should breach the guidelines ("The customer won't pay us if we don't do this" is, of course, a perfectly valid reason, and may be the case in some heavily regulated industries). And the guidelines should not be set in stone -- if a rule causes more problems than it's meant to solve then it should be easy to get rid of it. It should probably be harder to get a rule put in, but it should be possible. Neither of those is practicable for major, published standards such as MISRA C, so you need local standards.
I'm not sure it's meaningful to talk about coding standards in isolation, by the way. I consider it essential for serious development that the purpose of every function and its parameters be recorded, but whether that's done in a comment (in which case it belongs in the coding standards) or in external documentation (in which case it belongs in development standards) depends on the type of environment.
Quidnam Latine loqui modo coepi?
The only dabble in non-web programming I ever did was fiddle with Commodore Basic as a child. I suppose I was lucky enough to stumble upon one early article somewhere advising against the worst excesses of "Gordian-Sphagetti" code. I understood that as far as it went, and made some efforts to keep a simple enough main program and put the subroutines to the heavy work.
However, I never did understand how to write an entire program without a GOTO statement, because depending upon certain condition checks, it became time to restart the program at some point in the process.
The best I was able to manage was something like eight-ish GOTO statements per 1000 line programs.
I'll be looking to write some tiny widgety programs in the future, and I don't see why having a few GOTO statements is the total kiss-of-the-ZombieCode. I have no interest in pro-level programming.
My first Journal Entry ever, in 8 years! http://slashdot.org/journal/365947/aphelion-scifi-fantasy-horror-poetry-webzine
The prohibition on "multiple exits" or returns comes from a misunderstanding of early program proving technology. As one of the few people who ever built a real proof of correctness system, I know that's just not a problem.
There are some topological restrictions on program proving, but you can't violate them with "break" or "return". You need "goto" to really screw up. The actual topological constraint is that backwards control paths must not cross.
The basic requirement for proving loops is that there must be some section in the loop through which control must pass on every iteration. Somewhere in that section must go the loop invariant and the termination measure.
Nobody does this for software any more, although, interestingly, full-scale machine proof of correctness of hardware logic in VHDL is not that unusual. There are commercial tools for that.
.. after seeing 'Java' ? :)
The truth is, it doesn't matter what the coding standards are. The sole value of coding standards is to make the code all be formatted the same. Any standard will do that.
Code formatting gets a lot of people heated up in practice, but the amount of heat is disproportionate to the importance of the issue. The *code* is important; how the code is laid out isn't.
C++ Coding Standards: 101 Rules, Guidelines, and Best Practices
0. Don't sweat the small stuff. (Or: Know what not to standardize.)
Say only what needs saying: Don't enforce personal tastes or obsolete practices.
Any coding standard that does not self-regulate itself in this way is suspect. Nevertheless, there are still 101 good practices to enjoy. Buy the book.
What is specifically left _out_ of the standard?
Brace style, tabs/spaces arguments, which side of the equality operator to place non-const.
All the stuff of stupidity and pettiness.
Take a look at the MISRA-C for another coding standard. While I don't find MISRA-C all that compelling, at least it deals specifically with substantive choices (whether you agree with them or not is another matter).
.. "no tabs in the middle of the line" rule. Especially relevant in multiple variable declarations:
3.243F6A8885A308D313
Python people argue over tabs vs. spaces for indentation. In Python, where indentation matters, it's a major issue. Python implementations really ought to insist that a file have only leading tabs or leading spaces. Mixing of tabs and spaces is clearly wrong.
A big UNIX design mistake was to have a tab equal eight spaces. If it had been four, everything would have worked out better, since four spaces is a reasonable indentation amount. It's eight because, when outputting to a Teletype Corporation 100-speed printer (ASR/KSR 35 or 38), the carriage can reliably move eight spaces in one character time. So, if you set the hardware tab stops every eight spaces on the printer, this provides maximum output speed. That's the real reason.
For C and C++, just run the code through "astyle -style==ansi". Let the machine do the work.
Your function can be writen like this:
int multiply(int a, int b)
{
return (a*b);
}
Wow ... look at that ... no C&P needed.
Only bad coders/dumb asses write 20 lines of code for basic arithmetic.
I work in a Python shop... Some of the odder rules:
1. No more than 3 parens in a row.
Eg, map(len, foo(bar(x))) is illegal.
2. Set temporary variables to keep each code line simple. Eg:
result = function1(function2(...), param, [list, of, stuff])
becomes:
temp = function2(...)
temp2 = [list, of, stuff]
result = function1(temp, param, temp2)
3. Embedded SQ: put the starting keyword of each clause on its own line in a multiline string, eg ...
sql = """
select *
from table
where
"""
4. Add line breaks to list comprehensions at the "for" and "if" clauses. Line up the "for" just after the opening bracket.
settings = [line.strip()
for line in lines
if not line.startswith('#')]
The JSF coding standard is on of the best.
BTW: The only reason dumb ass professors (most who have never worked outside of the educational field) teach students to put the opening brace at the end of a line is to save print space.
There is nothing functional about having a hidden/hard to see/find opening brace. Braces are there to "wrap" the area of a control statement. If another person (developer or non-developer) spends more than 3 seconds trying to figure out where a control statement begins, then the developer FAILED to write maintainable code.
Remember it's not copying if you type it over and over again. That's the way I avoid my code copy issues, works like a charm!
The lead programmer required everything be indented with 2 spaces, making everything less readable and annoying. It is also incompatible with almost every single programmer's indentation in the entire world, which made it more annoying. In addition, we had programmers on the project who refused to comply and so the lead programmer spent time reformatting their indentation, to which other programmers would get angry and reformat his. It became a very large waste of time, and a source of contention and battle.
I think one of the important things to matter is that formatting, eg. brace placement doesn't really matter. The book C++ Coding Standards (just google it) first, rather 0th, rule is "Don't sweat the small stuff".
Any developer can read and write a format -- what *is* important is just be consistent within the file and do reasonable indentation, line lengths, etc.
What does matter are coding practices, eg. when or when not to make functions public, using smart pointers as much as possible rather than raw pointers (a C++ thing), or when to use a pointer to implementation to hide details. These things have more substantial impact on code.
Please, please, please, can someone explain to me why:
is clearer and "oh-so-more-readable" than:
Don't laugh! I've seen a similar exemple on one of the numerous "coding guidelines" one can find on the web. I've also seen code like this:
}
I am pushing it of course, but just a little! Recently I had to take a dive into such a code where 200-character lines were common...
I still try to understand why "modern languages" seem to hate underscores and common abbreviations althogether...
Oh yes! I get it now! It is to be more readable...
YAAC
I don't agree at all that putting braces on their own lines makes code more clear. My feeling is that the "waste" of vertical space is harmful because it makes it more difficult to get a quick overview of a code block.
I prefer my code to look fairly "dense" in the vertical direction, because I feel that this highlights the structure more clearly. Whitespace is important, but excessive whitespace makes code look scattered and gives you the feeling you have to chase it all over the screen. Most IDEs automatically highlight matching braces anyway.
I agree on using braces even for single statements, where it is not strictly necessary. This is much less confusing and error-prone.
I also increasingly find braces to be syntactically useful all by themselves, i.e. outside the context of control statements. Braces are useful to divide code in blocks that reflect its structure, and can help to delimit the lifetime of temporary variables.
See these:
http://www.python.org/dev/peps/pep-0007/ C Style Guide
http://www.python.org/dev/peps/pep-0008/ Python Style Guide
http://www.python.org/dev/peps/pep-0020/ " Readability counts."
I think python is the one language where "good code==natural code". Can't hurt to read the thoughts behind this ...
the worst coding practise has got to be the excessive use of error handling for things that shouldn't have errors. I hate try/catch in C# about as much as I hate On Error Resume Next in VB6. Yes, there was the old VB practise of wrapping error handling around a file size check to see if the file existed. If it triggered then the file didn't exist. The same thing has been found in .NET, try/catch an attempt to read from a dataset to determine if it is readable. If it throws an exception, it's not readable. What happened to checking beforehand? Sometimes that isn't even available! I've encountered code that has as many as five layers of try/catch where a few if/else lines could have eliminated the need for all of them. Now don't get me wrong here, it has it's use, but just go easy on the try/catch. Seriously.
</rant>
(something_is_true) ? do_something() && do_one_more_thing() : do_something_else();
ifs and braces are for girlie boy programmers!
I once had a colleague who insisted on using the following style for blockless-if statements:
if( condition )
statement
I figure you should either replace the above with
if( condition ) statement
or make it into a block as below.
if( condition ) {
statement
}
The colleague's approach (which she learned from her father, a university prof who probably never had to maintain somebody else's code) was just waiting for somebody to add a second statement (similarly indented) that really needed to be in a block to work correctly. Yep, it happened.
But in general, any reasonably skilled programmer should be able to either find or write a pretty-printer that will transform code to the desired brace alignment.
I believe its more important that your coding convention deal with issues like how are exceptions/errors handled (I really hate code that spends 90% of its time checking return codes), how much complexity is tolerable in a single function (having ported somebody else's functions that were several thousand lines long), how arguments are passed (Oracle's C functions for accessing blobs are a wonderful example of what not to do, something like 12 arguments to read a range of data), and unit testing.
First is the brace style, because this is most discussed. I use K&R style as everybody should. The whole notion of it being easier to read when braces get their own line is totally bogus. Any coder worth his salt will use consistent indentation, so all code will tend to look like this under *any* brace style:
if cond
stmt-seq
else
stmt-seq
Any style is readable. Also, I hate scrolling up and down just so I can see the rest of my statements because the screen is filled with filler lines with nothing but braces. And what is the deal with this madness?
if cond
{
stmt-seq
}
else
{
stmt-seq
}
Where is the motivation behind that? It is pushing me into crazy. I'm going to start licking my lips and doing pencil disappearing magic tricks (saw that yesterday). Also, the GNU brace style is just too complicated to enter. I use vi and sometimes notepad++ in Windows, and I can't for the life of me imagine how such a brace style could be done automatically. And even if GNU does it, Linux certainly doesn't. Personally, I am wary of any occurrences of the RMS and GNU acronyms.
As for managing horizontal space, it can depend on the language, but mostly indents should be eight column tabs and the screen is limited to 80 columns. Torvalds has a couple nice quotes I saw somewhere, but basically you're in trouble if you feel restricted by this. More than three levels of indents should be simplified into multiple functions, and really long lines are complicated to digest. An exception is Lisp or SML, where everything is an expression, and there are many many levels of nested parenthesis. I wrote a parser in SML, and I had to break down and resort to two character indents. Desperate times call for desperate measures.
Another problem is when people say that they have a widescreen monitor and they're going to use every bit of it with an 8pt font. So I have a 13" monitor: am I screwed? I'm sorry if I like my sentences and paragraphs spanning across multiple lines. The most effective way of coding anyway is to have four instances of vi on the screen at once (you use vi, right?). Sometimes I'll have the editor split so that I can be looking at two parts of the code at once. Most of the time, you're working on multiple files at once (like headers) or have man pages up anyway.
It doesn't seem like this has been discussed, but I also use the time-honored variable naming scheme of underscore-separated lowercase words. Camel case is just too hard to read, and it's inconsistent. Is it portTCP or portTcp? What the hell is Tcp? port_tcp is crazy easy. noXCoord or no_x_coord? (That's a point on one or two letter words.) For objects names, I do as Bjarne Stroustrup does in The C++ Programming Language: Capitalize the first letter, but do the same underscore style: Coca_cola_classic. That style I use mostly because whatever Stroustrup says or does in terms of C++ should be taken as gospel. An exception is anything you deem worthy of being a basic abstract type, like complex or hash.
comments shouldn't show up after anything but indentation on a line. The only exception is that it can be a short note about a variable. For example, you might want to write something like this:
struct range { /* noninclusive */
size_t start;
size_t end;
};
Otherwise you have a whole line for a comment, and maybe a line before that to separate it from the previous declaration.
The buggest one-day productivity increase I ever experienced in my own coding work was the day I finally stopped trying to use Hungarian Notation. Even now I'm amazed at how much it slowing me down. I got maybe 3 times the work done after the day I ditched that.
We know where leadership by an anti-intellectual "strongman" who scapegoats minorities and likes boisterous rallies goes
Hell, at first I thought (maybe hoped) the GP was being sarcastic.
Throwing more hardware at something just so you can write poetic code is foolishness. It's often lazyness, but I think in the GP's case it's stubborn idealism.
Code is written for the computer, and should accommodate the computer; comments are written for humans, so keep your poetry and prose there. Explain what you are doing in English (or Swedish, French, German, Swahili, etc.), not by making the computer jump through hoops each time a program is executed.
Speaking of stubborn idealism, if you ever want to start a usenet flamewar, post to one of the database groups questioning whether something belongs in program code or a stored procedure. The deontological nutjobs come out of the woodwork, advocating their absolutisms that completely ignore efficiency and the possibility case-specific solutions.
Most people's ... programs should be indented six feet downward and covered with dirt.
—Blair P. Houghton
This sig cannot be proven true.
"So tell me genius, how else would you implement such a function without copying? if (a==1)
{
x+=b;
}
if (a==2)
{
x+=b;
x+=b;
}
if (a==3)
{
x+=b;
x+=b;
x+=b;
}" - by 4D6963 (933028) on Sunday July 20, @10:17AM (#24261957) Homepage
Well, ok (even though I am not this "genius" person you are quoting!)
Case statements, anyone?
Specifically, switch & case, for C++ folks:
(An example that fits YOUR code example, & how it would benefit by this (for readability AND performance), per this page ->)
The Switch statement in C++:
http://www.awitness.org/delphi_pascal_tutorial/c++_delphi/switch.html
It'd be a big help for readability in your example(s), since you have a lot of a==1, a==2, a==3 stuff going on there (to aid in processing speed via break statements)... stopping excessive + unneeded evaluations from occuring!
(For NOT executing comparisons that do NOT need evaluation (by using the break statement to pass them by once a solution/situation that satisifies has already been found, saving processing time))...
Delphi (my fav) has CASE statements for this...
APK
Not in the code sense, but in the project sense.. I.E. I work on this, you work on that. We can ask each other for help, but this project is my baby and that one is yours.
I'm sure this is anethema to most coders, and that at some point it's not scalable, but it keeps inept coworkers away from my code.
No wonder you're confused...
I don't really care how others style their code. Eclipse (and several other IDEs i've tried) has a wonderful tool - a formatter. Ctrl+Shift+F, and the code is rearranged to my own coding style (which, by the way, is { on conditional line and } on it's own line).
Do not meddle in the affairs of dragons for you are cruchy and good with ketchup.
It has been used for serious programming. I'd venture most Slashdotters have come into contact with a program that was written like that. I'm not kidding - how fucked up is that?
When doing maintenance on someone else's code, use their style, even if it is one you hate.
But it makes the else look like an imperial fighter!
1) ! (K&R braces) // 'nuff said
2) when formatting expressions, put multiple spaces in parens () - depending on nesting level
ie. if ( ( exp1 || (exp2 & something) ) && (something-else) )
3) about variable names - no hungarian notation, please. If the type of the variable is not apparent from context, I can da*m well look up the definition, thank you.
A roommate of mine was working on a big project for a major telecommunications company, in a variation of Pascal. Their standard was to encode everything into the variable name - scope, persistance, type, and finally some sort of actual name. The names tended to be over 80 chars in length - making it impossible to simply scan the code. I heard they spent a lot of time in code reviews. I'm suprised they actually got the system to work.
If it is C code for embedded systems we are talking about, there should be no hand coding or hand integration of code allowed. Most companies are developing their embedded systems with Model Based Development using the MathWorks tools. RTW embedded coder will generate 99.9% error free code from the models. Using UniPhi and QuantiPhi from SimuQuest (simuquest.com) in concert with the MathWorks platform allows all drivers to be integrated in the modeling environment, in the correct time threads. RTW embedded coder will then generate the entire software for the ECU in one go.
Many companies today still make the mistake of trying to re-use old code. This is called infectious repetitis. This may seem attractive and logical at first glance, but does not take into account the massive effort to debug the hand integration and test on real hardware. Integrating and testing everything in the model gives you enormous confidence that the generated code will be correct. Confirmation testing is done on the hardware. If there are problems, either it is a hardware issue, or you need to look at your logic (in the model) or the accuracy of the plant model you did your algorithm development with.
I know that goto is "considered harmful", but when you are doing systems work, say an operating system kernel or piece of userland code solving a very systems-y problem, you are most likely working in C, a language that has no inherent support for exceptions (setjmp/longjmp doesn't count), and makes you reclaim unused memory by hand. So, for any sufficiently interesting function, you must allocate some memory, make a fair amount of function calls, check their return values for failure, and if they fail, deallocate everything, not to mention deallocate those same structures if you're successful too. In some cases, if you don't use goto, you can easily end up with long blocks of redundant code freeing everything at any point that something can fail.
So sometimes it's easier to do:
The other big lie is that functions should be short. That may be true for application programmers, but anyone who's worked on a big systems project can tell you that it's often an unattainable goal.
It bugs me that some people are so narrow-minded about "rules" they've heard against a particular practice that they're unwilling to see that the rules don't fit every scenario.
Well, in my opinion there are no best or worst way, what exist are the ways you like and the ways you don't like.
For example, I like codes this way:
if(expression){
}else{
}
Anyway, thats my 2 cents.
After more than 150 years of experience in software development, I have come to a very simple conclusion about coding standards.
Very good coding standard that is readable and maintainable: My standard.
Very bad, unreadable and unusable coding standard: Everything else.
So many rules, but still buggy.
HBI's Law: Frequency of calling others Nazis is directly correlated with the likelihood of the accuser being Communist.
The coding standard specified that programs could not use heap memory. A small exception was made for initialization code like this:
int size = readConfigFileForSize();
globalCharArray = new char[size];
Everything else was required to be coded on the stack. And STL was discouraged as well. This was moderately real-time software, but the no-heap rule was still rather draconian.
...because you're fuckin' fired!
That sort of coding attitude of "just throw more hardware at it" is the biggest cause of websites that can't scale to handle any real traffic loads. I've personally bumped site performance with just a few line tweaks and optimizing a few SQL queries.
Ask the machine to do something stupid, and it will.
Ever see someone write "SELECT SUM(ColA) FROM Scores WHERE QID = 3" on a high-volume site? Do you understand the impact just that naive query is going to have on the back-end server?
Here's a clue - you're going to end up with queries taking 30 seconds on that nice 8-core box with a RAID-10 array because you are constantly re-totaling 250,000 records and asking to do so 100 times a second. Time-out city coming. How about database table locks?
Any semi-decent programmer will know better, and actually use a decent algorithm.
You simply do not compromise your performance for laziness. And just because it runs fast on an unloaded test-bed doesn't mean it will work in the real world.
Try getting linked to by Yahoo some time and see what scalable means.
Or try writing an image processing filter with real response time restraints so you can send appropriate pan/tilt commands to the source camera. You need real code for that, not crap. And no, more CPU speed won't get you out of that one either, and no, you can't write it in Java or C#.
Yep, a good support for macros may be the best feature a language can have. It replaces all the OO features, with several advantages.
But, also, a good support for macros may be the worst feature a language can have. It leads to an unmaintenable mess where each part of a software is written on a different (unique) language and only the compiler can put it all toguether.
As aways, the outcome depends on your team.
Rethinking email
I worked for a company that was ISO 9001 and made a lot of noise about being so very ISO. Their coding standards were C only with extremely old coding styles that hadn't been used since the 70s. I am not even sure if those coding formats would even compile. The funny thing was that not a single employee was coding in c with the possible exception of a single individual who was doing some kernel hacking. Everyone else (hundredss) were using the usual mixed bag of languages popular at the time completely unaware that the company even had these useless standards. Yet a few times per year an ISO auditor would come in and say everything was OK. So to stir up some trouble I pointed out, to the auditor, that we were not following the C standards. I was ignored.
The only rule I've ever seen that matters: if you modify a file, keep the file's style consistent. Either code to match the rest of the file or (if you are making enough of a change to justify it), reformat/refactor everything.
Other than that, as a lead or manager I list "stop words" that should tell a programmer to show the code to someone else and explain why they did something unexpected (goto, operator->*, returns nested deep in the middle of a function, etc.) and pick whatever naming and indenting standard is common on the platform, but don't get worked up over it.
And the #2 rule (after in-file consistency): no standards discussion in code reviews. If someone violates common standards, tell them separately. Otherwise reviews can turn into nit-picky "move this here and change that prefix" 3p33n waggles.
Why?
Because I suggested to the managers that having some would be a good idea.
They had none. Zero. Zilch. Not a Sausage. All coding methods were left completely up to the individual developers whims and experience.
This was a software house that develops custom solutions for the world's largest legal firms. They are now part of one of the largest electronic information management corporations.
I was inheriting follow-on projects where half to three-quarters of the project time was spent figuring our how the previous developer did the task. I saw this as a problem and tactfully made suggestions that we may want to set some standards and start some regular developer group meetings to discuss those standards and ways of optimizing our development time.
Unfortunately the managers were only concerned that we put as many billable hours in no matter what the quality of the output which in many cases was absolute crap. My insistence that this was the case with more than adequate proof was not what management wanted to hear so the squeaky wheel was let go.
So the moral of the story: Coding standards are a good idea but if the house you're working for isn't ready to implement any, it's time to look for work elsewhere.
If you don't want to repeat the past, stop living in it.
Done properly, classes can do a great job of abstracting & encapsulating; too many classes (or levels of abstraction) can be extremely confusing and difficult to maintain.
C++ gives you just enough flexibility to create a masterpiece or to hang yourself. I recommend using polymorphism, templates, and inheritance sparingly. Many of these concepts work reasonably well for GUI-related stuff, but can often obfuscate more complex algorithms. The "use sparingly" concept applies to other concepts, as well -- "gotos", "unions", and so forth.
I don't see why anyone should have any coding standards at all.
Think of it this way - there are a million code re-formatters that do a great job getting code into whatever form you like to see. So why not let someone work on code that is the most readable and ascetically pleasing to them?
What really should happen is that operations to a source code control system all go through a filter that formats the code on the way in and out. Depositing source into a repository should format to a canonical standard that was acceptable - but anyone could re-format on checkout to whatever form they liked. Repository differences would work since the code would always have the same form. Diffs against you local changes could be presented against older code forms that were run first through your chosen filter so that diffs would appear in the form most pleasing to you.
So all coding standards would be essentially local, except for the people who chose to work with the un-tweaked canonical format from the repository. An additional benefit was when it was time for layoffs, obviously anyone who cared about the code so little they did not seek to customize the view they have of it could be the first to go.
"There is more worth loving than we have strength to love." - Brian Jay Stanley
///*
if( something ){// comment
doSomething();
}else{
do_Something_Else();
if(otherthing){
//comment
do_Other_Thing();}
}
//*/
All that matters is others can read your code; its all preference or religion.
Democracy Now! - uncensored, anti-establishment news
And then, like the compiler, ignore white space and concentrate in the semantics.
Rule 37 - No swearing in code comment sections.
it's about coding standards and all you can brag
about is how you brace your code blocks.
here's a coding practice you'll get more from than any bracing style:
"cat sourcecodefilehere | grep '//'"
that should give a precise description of what is going on.
No Hungarian notation.
We're in an age of log server worship, where debugging is buffered & takes 50 macros to get working & as long as the program doesn't crash before the buffer is flushed, you get your trace, assuming you got all 50 macros set right.
The Linus says:
"If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program."
<sarcasm>Oh well, if Linus says it, it must be true.</sarcasm>
I really hate this sort of dogmatic bullshit. Some algorithms are complicated, and don't factorise conveniently into self-contained chunks. It seems like every time we talk about function lengths or nesting depths or some similar issue, someone trots out the tired old lines about fitting on a screen, indenting to a certain level, or some such.
Now, let me be clear: most of the time, these aren't bad ideas as rules of thumb. I absolutely agree that you should pull code into a separate function if it's meaningful and self-contained enough that the purpose of the function is clear.
But if your code doesn't fit that description, for goodness' sake don't just yank out some part of it into a separate function because dogma told you to. That just spreads out an inherently complicated bit of logic so instead of at least being able to see it all in one place, you have to worry about jumping around into pointless functions that aren't self-contained or meaningful in their own right anyway, and is about the worst thing you can possibly do for readability and maintainability in difficult circumstances.
If anyone thinks they know better, I'd be interested to see your efficient generalised subgraph matching algorithm, and so, I would imagine, would a lot of the academic and professional mathematical community.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Every language has a grammar (of some sort) that determines how the code is to be broken down and ultimately executed. The problem is that there are multiple 'sentences' of grammars that produce exactly the same result when executed (e.g. the parse tree is exactly the same), because there are parts of the source code that have no effect on the execution (e.g. whitespace in many languages). Coding standards are really then about adding additional rules to the grammar to reduce the many exactly equivalent 'sentences' to one.
The problem with these additional rules is that the often times there's nothing in the tool chain that enforces the standard. The ultimate result is that programmers bitch at each other for not following the standard, bitch about having to manually apply the standard, or the standard is simply ignored.
What I want to know, is why does this all matter so much? Why isn't there tooling that will structure the source code to the way a particular programmer wants to see it rather than someone else's standard? It is structured data after all. Does anyone know of tools that do so? I personally haven't run across any (though I've also not spent tons of time looking, either...).
I like your current firm's approach. I'm 'classed' as an electronics technician. Which means in nearly all jobs it's almost impossible for me go anywhere near code. But I still do a lot of coding; it just has to be invisible.
I write a lot of small test fixtures with specialized embedded microcontrollers. For these tiny 'systems' to be efficient, they have to be small, cheap, very precise, and quick to program. I still do nearly all of my coding work in Assembler for controllers that cost less than $2. For example, a +5Volt/ground pulse that is exactly 40 seconds long (+/- 5 milliseconds) with a measurement of the time that it takes the voltage across an attached capacitor to fall to exactly +2.2V.
The senior engineer devised this test 25 years ago for final calibration on a piece of medical equipment. According to the old procedure, it takes about ten minutes to set up the equipment and run through the procedure enough times to get an accurate result. But with my Atmel AVR Tiny13 85-cent microcontroller, I get an accurate result within a minute. I've been using this particular design for about a year, but still haven't got the approval to make it an 'offical ISO-approved change in the test procedure'. So I have to do it in secret, and could get fired if management found out that I was using equipment and procedures that didn't exist when Saturday Night Fever was still in the theaters.
I code with lots of comments and paragraphs of text in comment blocks that explain what the code is doing. As much as possible, I want to be able to cut and paste code routines between programs in order to make the development process fast and easy.
I remove all 'magic numbers' from the code. But I don't use THIRTY_SEVEN as a constant for 37. I would use a very brief explanation instead, like FIVE_MILLISECOND_DELAY_VALUE = 37. Personally, I dislike Hungarian notation. It works only for Hungarian genius coders like Charles Simoni who have come to learn about computer programming after mastering a half-dozen languages previously, like Charles Simoni. A word is an actual icon by itself, seperated from the other word-icons by spaces. Putting random characters in front of the word that is the variable name destroys the ability to instantly look at the word-icon and know what it means. If the Hungarian notation prefix is so important, it should be in a different color of text from the actual variable name.
I wish that I had the luxury of hating the C language. I think that it is ugly, and difficult to understand. But it is slowly becoming the standard for microcontroller programming because there are so many individual types of microcontrollers in use. Each with its own assembler instruction set. So all of us 'secret-coder' electronic technician 'potentiometer tweakers' are having to become proficient in it.
Some things I tend to do that that I'm not quite convinced are good ideas, but I do them anyway:
// variable declarations lined up
// a method like this... no space before brace when after a paren
// control structures written the same as function calls (no space after if);
// one-lining simple conditionals
// and a try block like this...
// empty blocks without line break
// annoyingly verbose java getters and setters on one line if they're trivial
// I do this sometimes, it lines up and the inside of the if block still indents once from the condition,
// instead of indenting the second line further ahead and having the block un-indent
// When things take multiple lines I try to line them up... space before '{' here
class SpaceDog extends RegularDog
implements AdaptedForSpace {
private String name;
private CanineSpaceMission mission;
boolean bark(){
if(inThePresenceOfAtmosphere) return true;
if(Space.noOneCanHearYouBark()){
try {
frivolouslyAlterPhysicalLaws();
}
catch(NewtonianOutrageException e){
beSadButDoItQuietly();
return false;
}
catch(PtolemianOutrageException ignored){}
}
produceIllogicalArf();
return true;
}
public SpaceMission getMission(){ return mission; }
public void destroyEnemy(EarthCat earthCat){
if(EarthCat.inherentlyEvil()
&& earthCat.threatensCanineMission())
destroy(earthCat);
}
}
I'm not so sure about a lot of these habits... what do you think? Do you have any style habits you're not so sure of?
The best coding standard is to run a formatting script as you check in to source control. Then no one has to pay attention to it, just run their favourite format command as they open any code file.
Really you're micromanaging your code. If your programmers need a standard in order to read the code, you're already in trouble.
Lets all just agree to disagree. Coding styles are very personal. I think of coding as an art form. You would never force an artist to paint a specific way. I suppose a coding style could be looked at as paint by numbers for the less gifted coders out there.
Just agree on the astyle flags and don't give it a second thought. You can even get somewhat fancy and add astyle as a check-in hook in your revision control system.
Other than that, don't waste time thinking up clever "best practices" and "standards" that will be forgotten in three days or waste time talking to boring, self-important pedants on slashdot.
Some things are very useful in coding standards, IMHO. The problem is that mandating the finer points of brace placement and whitespace usage is not one of them.
For example, we write very portable C++ code at work, which is routinely built on several versions of several compilers running on several operating systems, where some of the combinations are state of the art and others are several years out of date. There are some standard language features that simply do not work properly on certain combinations, or that did not work properly back when this particular project was started, and which we therefore decide not to use at all to avoid either introducing portability problems now or having to retrofit all the legacy code to match what we'd like to do. These things go into our coding standard.
Anyone who wants to use a prohibited language feature can make a case for changing the standard, but will be expected to show that the feature now works correctly in all currently and reliably supported build environments. They will also be expected to show that using the feature where they want to won't undermine any more general conventions. A common example with new starters is that we refuse to use exceptions anywhere, ever, for one of our projects. It's not because exceptions wouldn't help: on the contrary, they would make things much cleaner and we'd jump at the chance to use them if we were starting over. But back when this project was started, using exceptions was unreliable on some platforms and had unacceptable performance penalties on others, and we aren't going to start retrofitting exception safety onto over a million lines of code now.
If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
Surely the Master Programmer asks to see the company's coding standards before accepting the job. Otherwise, he might end up in a position where he would be unable to follow the Tao.
you forgot about that. i liked the one in boost libs. usually as small as possible, but as strict as possible to accommodate interoperability.
I use these coding standards; they seem to work well in practice. Others are possible too, but I wouldn't get too hung up over minor differences; consistency is by far the most important aspect. It also helps if you've got documented pre- and post-conditions for all functions.
"Little does he know, but there is no 'I' in 'Idiot'!"
I will never understand the concept of putting so many spaces between the "ifs", the braces, the "elses", etc. How can you read the code if it's so spaced out? I also get rid of a lot of local variables by using the results of a method as the input to another method, etc. It can reduce the lines of code to where you only have to decipher 1 line.
if (condition) {
_____do something;
} else {
_____do something else:
}
See, much nicer to read than scrolling up and down. Those who use so many white spaces "can't see the forest for the trees." More code on screen = better reading. (Ungh, couldn't indent w/o _____)
Let's not use exceptions but use a C++ integer named "ok" with an initial value of 1. Now write code like this:
int ok = 1; ...
if(ok)
ok = MethodCall();
if(ok)
ok = expression;
return ok;
They argued it was easier to step over in the debugger and it saved you from checking code exits (code exits only allowed in the last statement).
In Java Eclipse you can click the return value and all method exit point show up (including those for checked exceptions). For those Java programmers missing this brilliant feature.
Why not just have:
if ( flag )
salute();
And save an extra line?
Single-line ifs can introduce logic errors when you have to add an extra statement or when using a poorly written macro.*
if, else, for, and while should always be accompanied by braces to clearly define what they do.
* consider the following:
#define foo() if (flag) do_foo()
if (condition)
foo();
else
do_something_else();
I am a leaf on the wind. Watch how I soar.
I suggest making choices that are diff friendly. I recently switched to keeping { on the same line as if/while/do/... when I realized that in large projects that sometimes makes the difference between a diff that makes sense and a total mess. I prefer when \t can be used to indent and spaces are used to format. The main thing is to just be consistent and enforce what makes sense.
The first and foremost rule of good programming I've taught to my staff is:
**GET RID OF DUPLICATED CODE**
Every piece of duplicated code is a carnal sin. Even if a single line of code is duplicated, this is an offense. Deduplicating code has the following benefits:
* Usually results in less code to maintain
* Code you've written before is easily accessible to code you write in future
* Less errors - if you make an adjustment to the code but forget to adjust it in all the other locations, bugs can make their way into production ("I'm sure I fixed that bug!?!")
* It naturally results in a more structured architecture, which is vital for enterprise systems (or almost everywhere, IMO)
Recently we outsourced a project to a software house. When they returned the code, I found that huge, huge chunks of code had been duplicated, all over the place. After much profuse swearing, I rewrote the software myself, from scratch, making the program more functional, friendly, flexible and reliable - and in about a third as much code.
I'm obsessed about this principle, and take it to an extreme, and it's treated me exceptionally well.
actually talents communicate by thinking model
not by eye-reading
u read something by brain
not eyes
sorry
coding stds......actually not really needed
becoz if 2 ppl think the same thing in the same way....they can write the same thing in the same way
Here are some VB.Net and general coding standards that I made and try to stick with when feasible. I have been programming for 11 years and have been burned, time-and-again by these mistakes from myself and others. Some of which are obvious, but others may take some expericence in to fully grasp the implications of not doing them.
Never use a ForEach if you need to change the element iterator value or original group dataset, it will crash.
Never substitute enumerators with hard-coded literals or constants (unless you like Find & Replace).
Never reference member variables (regardless of scope) that are controlled by Class Properties; instead call the Property itself so that it can perform any encapsulated instructions.
Don't confuse the branch short-circuiting effect of an ElseIf, with two seperate If statements. Always check your flow control.
All Functions must return a value in all execution branch paths.
Unless you need to save time and code, implement class properties instead of public member variables.
Reserve the use of early-branch termination for cases in which the looping construct is otherwise uncontrollable/undeterminable (or excesive use of nested If's).
Always check the parameters to a function, method or property for validity before usage. Check for null references and valid data ranges. If they're not correct throw an exception to the caller with a descriptive enumerated-interface message that would be useful programmatically.
Whenever possible limit the parameter-less constructor (or any function for that matter) to only generic initializations only; this allows for maximum re-use in overloaded versions. (Implement the specific assignments in overloaded versions.)
Always initialize variables in the parameter-less Class Constructor; while declarative assignments might be equivalent, those values can be overridden later in the constructor unexpectedly by another developer.
Never return a "failure flag" from failed critical-success functions; throwing an exception will force the caller to resolve the issue that might otherwise go unchecked, the application generated exception should provide an interface error enumeration to allow easier identification of the root cause programmatically.
If you have many classes with only one data binding point for each, consider implementing a generic interface for data binding re-use; this helps separation of concerns by abstracting the specific function names.
All input parameters should be Escaped Names [], this allows an easy and clear method of identification for a target source within a functions scope; this helps to elminate reference ambiguity (for purpopses other than escaping reserved keywords).
Take advantage of generic instance keywords: Me/This, MyClass, MyBase. Instead of naming member scope varibles with m_; this helps to elminate reference ambiguity.
All variables being used for function returns must begin with an underscore or other identifier to allow clear identification of its purpose within a functions scope (in contrast to non-returned data).
Always use descriptive naming, but try to keep the length reasonably short.
Use Hungarian notation only if you plan on reading code print-outs a lot, or for compilers without IntelliSense.
Take advantage of compiler keywords that implement automatic resource disposal whenever possible, database recordsets and connections would be a good example case; note the class must implement the "Dispose" Interface.
Whenever possible implement Enumerations, member scope Constants/ReadOnly variables; they will centralize your statically-typed definitions and increase readability. Never use literals, this includes error messages and design-time default control values.
When importing namespaces, always leave at least one level remaining; this is to reduce the chance of reference ambiguity and increase readability.
Do not store Property member variables at the top of the Class; instead they should be
Personally I write stuff like
if
(
a > b
)
{
doSomething();
}
else
{
zomg();
}
Then I charge the client 5 * the number of lines in a all source and header files.
"Ubuntu" -- an African word, meaning "Slackware is too hard for me". - stolen from Dan C alt.os.linux.slackware
Let's make a language where you MUST use newlines in every circumstance imaginable, and if the compiler detects a lack of a newline where there ought to be one, a picture of an old lady sticking her tongue out at you appears.
Like this:
if
{
$message
==
"Enjoy!"
}
then
{
print:
"You too!"
}
else
{
while:
{
2
>
1
}
do:
{
print:
"HEY YOU DIDN'T TELL ME TO ENJOY!"
}
}
Please, PLEASE just use consistent casing/underling on function names!
My current work has hundreds of classes with methods like: ... ...
GetName()
getAge()
get_address()
CalcTotals()
calc_totals_for_user()
Not only does it look hideous and unprofessional, it requires looking up the exact spelling every time you need to use one.
If nowhere else, please at least keep the INTERFACES clean with good coding standards. Everything inside can be as ugly as hell if I don't need to maintain it. If I need to use your interface however, I damn well want it to be clean!
if(x>5){doSomething();}else{doSeomthingElse);/*real programmers dont need new line or any contigous spaces*/}
this style makes your programs smaller and run faster!
You speak London? I speak London very best.
My team does almost 100% maintenance programming. It's rare that we write a new program.
The application has been developed, in C, over the last 20 years.
Our coding standard is "try to figure out what the file you're in mostly looks like. Do that."
The preferred solution is to not have a problem.
At my shop there is a convention (for some projects) of one routine/function per source file with the source file named from the routine name. The reasoning is that you can find the source file easier given a function name. This coding standard was implemented over 25 years ago for FORTRAN and SIMSCRIPT projects. The principal engineer tries to enforce this coding standard on contemporary language projects, and can't understand why the convention is a really bad coding standard for C, C++, Java, or any other modern languages (not to mention impossible to follow for object oriented languages) . Some of us have some really goofy coding standards to deal with (or simply ignore).
When I worked at autodesk, the code had to compile on a huge number of target systems, so coding standards were about not breaking the code on systems with crippled compilers. It led to sad code,, but allowed autocad to compile on just about anything. Portability is very important, and standards help with that.
Famous quote: "I might not be able to define it, but I can recognise it when I see it."
Bad code is the same, especially when it is used as an example of good code. Just take a look at this.
Let's hope this guy's employer doesn't pay him to code.
Good judgement comes from experience, and experience comes from bad judgement.
- W. Wriston, former Citibank CEO
I just undid a mess like that a couple of years ago (a mess I had introduced several years before that). It was very gratifying to see the dual-maintenance problems vanish.
Patrick Doyle
I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
Recently I prepared some code I'd written in Objective-C for use by another developer. They were licensing the source and wanted me to use their coding guidelines where possible. One of these had me scratching my head.
When objects are instantiated in Objective-C, the runtime implements the language specification that states that all data members are initialised to zero. In the light of that, the developer's insistence that every member variable be ASSERTed to check that it really was zero seems ridiculous. I mean, if you can't trust the runtime to do what it says it will do and what the spec insists that it does do, what can you trust it to do? By that logic the only safe way forward is to start by implementing your own runtime...
The developers argued that ASSERTs are not *supposed* to execute, so it's not as if they are slowing things down... But I really think that seriously missed the point. One practical effect of adding all those ASSERTs at their insistence was that it made any initialisation code that set things to non-zero values much harder to pick out, read and check. Now that particular customer has moved on, I'm gradually removing all that pointless clutter as I re-encounter it...
Actually, "a single point of exit" is the whole of the law for being a "structured program" in the classical sense.
From the practical sense, it makes debugging happier since you have one place to put a breakpoint.
What most people call "refactoring" I usually call "code origami" because it is a useful moment to apply both science and art. 8-)
Consider the average function returning bool. Fro the most part, if you can determine that a function is either "normally true" or "normally false" and then all of your structure analysis can be in terms of "varies from true" or "varies from false" (e.g. you start with "bool f() { bool retval = true; return retval;" as a normally true function and find the false cases as necessary.
When you find that "normally true" and "normally false" logic is intermingled, you instantly know that the function should be split.
When you add other rules like "a function either does or decides" (e.g. decision structure is different than computation etc) and so on, you get lots of natural divisions for your decompositions.
Oddly, this is exactly orthogonal to the functional programming model where iterative collateral definitions of a function bodies with guards, reduces the code body to declaratives.
So anyway, the prohibition doesn't come from misunderstanding of early program proving technology. It comes from the root theoretical work relating to state isolation and "demonstrable correctness". That turned into some of the early provability tools. But there is a difference.
Innocent people shouldn't be forced to pay for inferior software development.
--"Code Complete" Microsoft Press
No, really. You can overdo it this way, severely limiting senior developers capabilities. For example, a C++ project I worked on several years before had the following guidelines, which obiously were designed according to your focus: Multiple inheritance was banned (whoa, dangerous). Result: Couldn't combine object hierarchy and technical interfaces. Templates were banned on reason of "code bloat problem". Result: Superfluous copy-pastelike code (bloated anyway). So sticking to these guidelines made good design somewhat tricky. We ended up restructuring the rules, going for "rules" of code formatting and naming conventions and "guidelines" for preventing buggy code. Each rule and guideline was supplemented with reasons for this rule, examples, and a list of conditions permitting rule violation.
http://en.wikipedia.org/wiki/Indent_style
I think this is a must-read for anybody talking about coding styles, although the article's title is somewhat misleading.
It also explains why K&R is actually not the coding style used by K&R in their code - it was the first C book editor's choice to reformat the code so it takes less space on paper, without any thought about readability or other criteria, and without consultign with K&R. Many monkeys reading the book and using the code style afterwards led to the spread of this awful style, not the guru's preference for it.
Hungarian: I always used it, and found it useful. However, Hungarian may mean different things in different languages/environments, so you have to come up with your own conventions. Dumb conventions, in place just for the sake of it, aren't really useful.
Line length: due to physiology of reading, no matter if on screen or off screen, lines should never be longer than 70 characters, and typically at most 40 characters. Reason behind it: when you read, you don't glide your focus along the lone, but instead focus successively on fragments on lines, the length of the fragment depending on your reading habits. When reading code, programmers instinctively tend to span a portion of a text line large enough to grok one line at a time, if it's not too long - it ensures that most of the times the portion of the line constitutes a semantically complete unit. If you make lines longer, the physiological inability to focus at once on too long a line will make you build up one semantical entity from more than one piece of text, which is more effort. If you break lines too often, you will be in the same situation, not because you couldn't focus on more characters at a time, but because you aren't used to focus on more than one line at a time.
This is also the reason (actually, my reason) behind braces on separate lines. A brace says "begin/end block". An else, if or something else, is a different concept. If I mix them on one line, I confuse the later programmer which will be reading my code, whether you believe it or not.
Reasoning such that too much white space allows for too little code on screen I don't buy. You have large monitors nowadays, and if you still don't have enough vertical space on your monitor then probably your code isn't well factored.
Just to set things right, I'm not an anonymous coward, just lazy - creating an account means work.
Oh god, please don't share your ideas!
Rules of thumb:
1. Proper indentation
2. Proper comments
3. Proper blockstructure
4. No code block exceeds a screen page (80 col x 25 lines)
The first three should be obvious, I hope. No. 4 is about legibililty for everybody involved. It may well be that you feel comfortable with very long lines and use a small font, so you can hold 200 lines on screen, but the common minimum standard is still 80 x 25, and some people still prefer to use that format.
The worst standards are the ones that have too many details - it's like micromanagement. Trust your coders to do the right thing, but enforce a few, important rules. The way source looks should only be a matter of importance if it helps make the code more understandable and thus easier to change or debug.
I have my own preferred formatting and naming styles, and I use them for my own code. When I work for a company, I use the company's preferred style, if they have one (though I'll happily fall back on my own). Anyone who can't cope with that simple logic probably doesn't deserve to be working at your (or any) company. Certainly anyone whose productivity is impaired when they're not working in their own preferred style is probably overpaid.
In a java class the teacher taught us some conventions that we were supposed to use for the class (although we were allowed to use other conventions if we really wanted).
Instance fields were my_something
Parameters were the_something
static final things were WHATEVER_VARIABLE
Class names were ClassName (and thus consistent with most other classes)
method names were methodName (also consistant with most other public methods)
Also, the variable names were supposed to be very descriptive (for full credit), such as, for example, my_brush_color (paint clone), or my_current_piece (tetris).
I really liked these conventions, and still use them whenever I can. I feel it makes the code easy to maintain and read.
If we're talknig about simple single if else statements great. But more often than not, one gets a convoluded nested if, which for readability purposes could be often beter used in case arrays One practice I came across was that if the algorithym had more than 3 nested if statments then we used a case array
:1(do something)
:2(do something else)
:3(do something else)
:4(do something else)
:5(do something else)
:6(do something else)
case(1,2,3,4,5,6)
{
}
Some coding standards are just common sense and its sad that there are a crap load of developers/programmers without much of it. E.g. I work for a major financial institution and have seen extremely bad habits such as a 3,000 line method. I mean in all honesty, just one look at the code (even with great IDE's that can navigate to closing curly braces) you get so worn out before even debugging. What's sad is that the culprits churning out such crap are Senior Developers. I think emphasis should be placed on modularizing your code. With modern IDE's this is not much to ask for.
Coding style is totally subjective, hence discussing it is almost pointless. So I offer just a few (meta-)observations from 20 years in the trenches:
0. For senior developers, terse is still quite understandable, and hence "better". More stuff on the screen at one time = good.
1. For beginners just learning a language's idioms, or developers who aren't that bright, cut/paste is more understandable, hence "better". It may take up more space, but each line is more easily comprehended in isolation. (I have seen developers with 10+ years of experience, still coding heavily with cut/paste.)
2. If a team of headstrong people already use diverse styles, imposing a standard will create ill will.
3. For a team of easy-going, mature developers, a modest coding standard is welcomed.
4. Everyone will argue for the form they are most comfortable with, and that is totally subjective. Sure, we can cite nice sounding reasons for our preferences, but the opposition can do the same. (And is it always the case that the smartest carry the day?)
5. Yes, there are styles that are "way out there", but those coders won't speak up. They will just keep coding in their style, hoping nobody notices.
6. Until there is a way to measure the average cognitive effort required to understand a given style, relative to other styles, we may as well drop this debate and do something more useful with our time.
It all adds up to lost profits for some, and job security for others. Ain't life grand?
This sort of ant-scale concern is just too trivial to waste time on. Instead of chasing around trying to make everyone put their braces where you want them, spend the time on good code reviews, good design, and other things which actually ARE important.
Coding is MAYBE 10% of the total work involved in creating a piece of software, and by far the least critical 10% at that. Even in the category of coding practices such trivia as what you name local variables and how you indent blocks is at the very low end of the scale of importance.
I started out coding in FORTH, and I really do believe that experience taught me a lot. Never make a function more than 5 lines long. If you have 40 lines of junk inside a block, it should be a function/method of its own. NAME things descriptively and design your APIs to expose WHAT people want to do and not HOW it is accomplished. Learn and understand patterns and refactoring.
Forget about where the stupid brackets go. No one coder should be the only one working on a piece of code anyway, the whole team should be looking at it within 2 days of its birth. So if your process is right, then code style will just naturally converge to a consensus.
"Malo periculosam, libertatem quam quietam servitutem." -- Jefferson
Just to add a little ancient history in this area:
Long long ago, there was an international Usenet workgroup that formed to create a universal PKZIP-compatible zip compressor / decompressor utility. We were getting tweaks and hacks from all over the place (for different systems and compilers, as well as actual functional improvements and bug corrections). And we were posting not only full source updates, but also the latest and greatest changes as diff files. (Remember them?)
As a result, we couldn't have make a decent diff when someone had changed 3-space indents to 4, or tabified the code, or uppercased all the constant names. So we'd run all the received code through a utility / script that would set "standard" indents, cases, wraparounds, etc. THEN we'd do the diff against the old version.
For a year or so I was the coordinator / moderator, posted the source (to good old SIMTEL.NET), distributed the diffs, etc. And I wrote up the "No Feelthy" rules (e.g., "No Feelthy Tabs") to give everyone a baseline.
There's some history here:
http://mit.edu/~mkgray/jik/sipbsrc/src/unzip-5.12/ZipPorts
As you can see, they've updated it (and even gave me credit, hooray!) ... but still kept it pretty simple.
Heh .. funny to re-read all that after all these years. (It has been a VERY long time.) Real Stone Age stuff, I know, but there were some serious limitations back then that people don't even know about today! (Yeah, and we had to walk through 4 feet of snow to school, uphill both ways!)
Yep, those were the days, all right. [kaff][kaff]
David Kirschbaum
Former Info-ZIP Coordinator
Our company does not have coding standards. But every once in a while, we're told that something is "supposed to be standard for everything!" Then we have to go back and rewrite everything we did previously to match...
It's very efficient. Like hamster wheels.
The purpose of "coding standards", as opposed to "design standards" or "best practices", is to make the code easier to read and understand by making the formatting consistent. But, unique people with specialized education or experience are, well, unique. Each person has unique background, preferences, and habits.
So the meaning of "easier to read and understand" is different for each person who has to read and understand the code. Forcing a programmer to write in a style other than his/her preferred style actually increases errors. And, forcing people to read thing written in styles that they don't like is likely to slow them down. So the right answer is to allow each person to read and write code in his/her preferred style, and to have a tool that puts code into that style on demand.
We use "uncrustify (http://uncrustify.sourceforge.net/ ). Uncrustify is, basically, a feature-rich, flexible, and configurable "beautifier", that works on several C-like languages. It puts code into whatever style the user likes, based on a configuration file in the users home directory. By using uncrustify, each programmer can read in his/her preferred format, even if it is different from the authors preferred format. This minimizes format-induced errors, maximizes ease of reading and understanding.
It also avoids silly arguments about code formatting, so we can spend our time arguing about more important things, like meaningful variable names.
Hi,
Long time reader.. first time poster but when I was reading the story and saw "or that code should be indented with tabs rather than spaces, or vice versa" and knew I had to post this story...
My friend had to go through some code at work one day and called me over and said "take a look at this". As we tend to show off bad examples of code (and there is lots of examples to show) I knew it had to be awesome b/c it warranted a live example as opposed to a verbal / written story.
The code looked something like this...
if(something){ move this field to that field move another field add some fields } etc etc etc.
We looked at the the comments up top, saw the developer and for some reason decided to change the resolution to match her resolution (800X600!! - who the fck uses 800X600?!). The code then lined up perfectly... she used spaces to go to the next line!!!!! Probably the best example of coding I have ever seen in my short 5 year career.
I have seen good and bad looking code from good coding standards. The best idea that I can come up with is: as you are writing the code realize that you are writing it for 2 things, 1. the computer and 2. the next guy that has to look at your code. if you do this then your code will be efficient and easy to understand; this is after all the goal of a coding standard
Tell the engineers everything gets coded in .Net, but you can't use Visual Studio.
It's like watching a deer in the headlights.
Pascal was built for that specific model of structured programming, but it's not a correctness requirement. As long as all the exit points go to the same place, there's a "single point of exit", even though it's reachable by multiple routes. "break" and "return" all lead to one exit point, so there's no real problem.
Exception handling, however, does bypass the return, and adds some interesting issues.
I have been coming to this website for years and saw this article and decided to make my first post when I read the line "or that code should be indented with tabs rather than spaces, or vice versa".
My friend at work was asked to look at some code one day and called me over to his desk to witness a masterpiece (we normally show off bad examples of code to each other for laughs). Right away I knew it was going to be a good one as it warranted a visit and was not communicated via email or office communicator.
I looked at the screen and it appeared something like this:
IF( something equals something ) {________ then
move variable a to variable b;______ do something else;________ }
**Personal note: The underlines are spaces.. I got owned by the filter
I was amazed... we tried to figure out what the f was going on. We looked at the comments to figure out who wrote the code and then decided to change his resolution to her resolution (which was 800X600 - who the f uses 800X600?). After the change in resolution, the code lined up perfectly. So she used spaces to proceed to the next line of the editor.
She still works here..
When I worked for we were working on an *nix project. This was fairly new for the company which typicaly produced Mainframe products. One of the Company Software Requirements was that a copyright notice had to be within the first 512 bytes of every program and object module. ... but I'd never heard of it before or since ... I think it was some Lawyer's interpretation of some 1950's law ...
I'm not talking about the source code, I'm talking about the exe's (a.out's ) and objects (.o's) and shared libraries (.so's).
Supposedly this was some kind of legal requirement for all software everywhere
Naturally, Big Company's Mainframe Software had a compile flag to do this ... so it was no big deal. But we were using C and there was no such concept of forcing an arbitrary string into the first 512 bytes. So ... some "creative" individual found a way ... by declaring a global static function like
static void aaaaaaa_Copyright_1980_International_BigCompany_BlahhBlahh() { }
we were able to comply with this coding standard ... the linker's would sort the function names in the a.out headers and this one function name would happen to (usually) be in the first 512 bytes of all output files. So we had to include
#include "BigCompany_Copyright.h" .c file just to make sure ...
in every
And then ... we had to do some tricks to make sure the function wasnt optimized out in the final link pass ...
To reiterate: matching braces should line up horizontally AND vertically.
That doesn't make sense. If it is the same column and the same line as the opening brace you either have more than one closing brace or it is in the exact same position as the opening brace. This is difficult, even in editors that support overstrike characters and results in nothing being beween the braces.
On the other hand: code that isn't there can't possibly include any errors.
The consensus of the posts I read here seems to be that coding standards regulate code layout and are not very useful. My experience is different.
I was part of a small team that wrote the coding standards for C++ for a medium sized part of a really large company. We designed the standard to be usable throughout the whole company though. We took three years to complete a set of about 150 rules. None of them is concerned with code layout or a mere matter of taste.
But I suppose it is a C++ thing. No other language contains such a vast array of error prone constructs. Many of the rules in the coding standard are merely help to keep you out of trouble. We mandate not to use C-style typcasts for example, we require you to use assert() and we ask to use "-Wall" and other means to make errors detectable at compile time.
I think languages like oberon, pascal, java and other better designed languages would reduce our set of rules to about 3 or 4 basic suggestions like:
Let names of variables indicate the meaning of the object rather than its type.
Your coding styles are both pretty.
I don't use curly braces unless I'm performing multiple lines of code for a condition or loop
//None of this a=a+5 stuff //I shift integers when multiplying/dividing in powers of 2 (in this case a/=2 or a=a/2) //I use ++ and -- when simply incrementng/decrementing. None of this b+=1 or b=b+1 stuff
//a "continue" would replace this in a "while (1)" //jump to my condition code, as its a waste to repeat same functionality, or the overhead of passing variables and pointers to a subroutine
bool myfunction(int a,float b,char *c) {
if (true) something;
else something;
if (true) something;
else {
multisomething;
}
if (true) {
multisomething;
} else something;
if (true) {
multisomething;
} else {
multisomething;
}
a+=5;
a<<=1;
b++;
//I like my goto loops only when there is no condition immediately testable at the top or bottom. a "while (1) {}" would suffice, but feels wasteful (an always true condition test)
//I reverse indent my labels, and indent the code further than the previous-to indent
loopTop:
stuff;
stuff;
if (condition) {
badCondition:
stuff;
stuff;
goto loopTop;
}
stuff;
stuff;
stuff;
if (condition) goto badCondition;
stuff;
stuff;
stuff;
if (condition) goto badCondition;
stuff;
stuff;
goto loopTop;
loopEnd:
return true;
}
from 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
to 45 2F 6E 40 3C DF 10 71 4E 41 DF AA 25 7D 31 3F
Use whatever style you want. It is getting pp'ed before commit, however.
Other than that, the rules are minimal: no Hungrarian notation. No all capital identifiers.
Carry on.
I am very small, utmostly microscopic.
One of the best things for a programmer: learn to type. Among other things, it becomes natural to use longer variable names that might actually be half-assed descriptive. A current project has procedures with names like SetDefaultConfiguration(). Three guesses what that does. :-)
One bizarre coding standard from an earlier project set a maximum length on variable names, Since they had mandatory prefixes to say what component they came from, this did not enhance readability.
This stuff is here to serve us, not to bind us. If coding standards become too onerous, the advantages in development and maintenance effort are lost.
I still think Hungarian Notation is a crock.
...laura
Just remember:
Real programmers can write FORTRAN in any language!
"I don't care about the Constitution!" --Bill O'Reilly, November 17, 2009
Some thoughts:
Try to follow the established style(s) of the language until you're an expert.
Don't fight frameworks or spend a lot of time hacking around their deficiencies. If you have to work very hard to do something simple; you're doing something wrong.
Code generators should be highly limited in scope; they should only touch a single layer of your application at a time. This is because code generators tend to be quickly written and make lots of assumptions; code generators that dominate many layers of scope will be a nightmare when assumptions fail.
Don't write lots of class hierarchies that are highly similar. The code needed to martial data between types is error-prone and labor-intense.
Nothing comes for free.
No, I will not work for your startup
Coding standards are a good idea, but how do you measure the effectiveness of using the standards? Does anybody know of any studies on the subject?
First off, I'd suggest printing out a copy of the GNU coding standards, and not read it. Burn them, it's a great symbolic gesture.
MOD THE CHILD UP!
Some of my personal examples:
When I opened the employee file for a payroll application, I used the filehandle "the.downtrodden.masses."
One of my favorites was when I assigned a few variables ahead of time and was able to write (and use):
open(the.pod.bay.doors, please.HAL) else print Im.sorry.Dave.I.cant.do.that
Contributing to a happy workplace is essential to good code!
On the one hand you take life too seriously, and on the other, you do not take playful existence seriously enough. Seth
The MS STL looks like a mess. All identifiers begin with an underscore, braces are indented, some structure such as try blocks are not indented, and names are not especially descriptive (_Xlen, _Umove, _Alval?). Here's typical code from vector<T,Allocator>...
// TEMPLATE CLASS vector // varying size array of values
... // determine new minimum length of allocated storage // result too long // not enough room, reallocate
// destroy and deallocate old array
/* _HAS_ITERATOR_DEBUGGING */
template<class _Ty,
class _Ax>
class vector
: public _Vector_val<_Ty, _Ax>
{
public:
void reserve(size_type _Count)
{
if (max_size() < _Count)
_Xlen();
else if (capacity() < _Count)
{
pointer _Ptr = this->_Alval.allocate(_Count);
_TRY_BEGIN
_Umove(begin(), end(), _Ptr);
_CATCH_ALL
this->_Alval.deallocate(_Ptr, _Count);
_RERAISE;
_CATCH_END
size_type _Size = size();
if (_Myfirst != 0)
{
_Destroy(_Myfirst, _Mylast);
this->_Alval.deallocate(_Myfirst, _Myend - _Myfirst);
}
#if _HAS_ITERATOR_DEBUGGING
this->_Orphan_all();
#endif
_Myend = _Ptr + _Count;
_Mylast = _Ptr + _Size;
_Myfirst = _Ptr;
}
}
</ecode>