Best and Worst Coding Standards? 956
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?"
Keep it simple! (Score:0, Insightful)
Re:braces (Score:4, Insightful)
Nice, embed php code within HTML. That's bound to be fun debugging. Having to skim through thousands lines of html to find some embedded control statement.
And you complain about the placement of else...
Well hungarian notation... (Score:2, Insightful)
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
Re:braces (Score:5, Insightful)
It doesn't really matter what you do, so long as everyone on the team does the same thing.
developer buy-in (Score:5, Insightful)
Without developer buy-in, whatever coding standards you come up with will be useless. IOW, ask your developers to create the standard together.
Re:Keep it simple! (Score:5, Insightful)
Make it "cut and paste" friendly, and as small as possible.
That's a really bad idea. Cut and paste causes code cloning, which is among the most difficult maintenance problems.
Code should be designed, when possible, in small chunks (methods, functions, etc.). This keeps the need to think about refactoring to a minimum, since the code is already factored. Well factored code has many other benefits, including easier-to-write unit tests and better understandability.
I maintain software that was originally written by someone as a prototype and eventually given production status. 4 years later, I am still pulling bugs out that relate to code cloning. Think of the guys who will maintain your software, please.
Re:braces (Score:2, Insightful)
I see your quotes but this whole idea of one being better than the other is asking for a fight.
I find it much easier if you're happy to easily switch between whatever people want (within reason). As a Computer Science student, seeing how difficult it is to read code not in a format I usually write, why would I want to make it harder for the person marking my work?
Re:braces (Score:2, Insightful)
unless you're using a 12 inch monitor, they extra lines aren't really hurting anything. braces show where code blocks are, and blank lines are used within those blocks to break up the code into logically separate blocks.
Re:braces (Score:3, Insightful)
If you ask a bunch of 3 year olds which looks best, they seem to pick K&R and can point out the structure better than the extra line feeds or white space in other coding formats.
Are you serious? if you're going to make a bullshit claim like that, you could at least try to fake a citation. a three year old isn't going to know what they're even looking at, let alone knowing how braces and whitespace are used to group code into logical blocks.
Re:braces (Score:3, Insightful)
Not them, and that is a good enough reason.
Re:braces (Score:5, Insightful)
The code is important. The braces are syntactical sugar.
Re:braces (Score:3, Insightful)
yes the code is important, but knowing what code gets grouped and being able to follow the flow is just as important.
Re:braces (Score:4, Insightful)
I do something similar, but put the braces at the same tab as the conditional.
if(something)
{
do_something();
}
else
{
do_something_else();
if(otherthing)
{
do_otherthing();
}
}
It just boils down to preference.
Re:braces (Score:2, Insightful)
If the PHP is for presentation, yes, that should be where it goes. Further, if you have a thousand lines of HTML, you're doing it wrong. Would you prefer they embedded the HTML way back in the logic? try finding THAT and changing it.
GNU Indent (Score:4, Insightful)
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.
Re:My new standard (Score:3, Insightful)
Re:braces (Score:5, Insightful)
There are other good reasons for putting open braces on their own line. The biggest is that most coding conventions have a maximum line width. If you have an 81-character line, you need to break it. When you are scanning down the code, all you see is a line at one indent level followed by another line indented more - you need to read the entire line to tell whether it's the start of a block or not. With braces on their own lines you can tell just by visual pattern matching where every block starts and finishes.
While I'm in holy-war territory, I'll also chime in on the tabs versus spaces argument. The tab character has a well-defined semantic meaning. It means 'indent this line / paragraph by one tabulator.' If you are indenting anything there is only one character you should be using - tab. It does not, however, have a fixed width, and should therefore never be used anywhere other than the start of a line or for aligning two lines. If you have to split a function across two lines, you should indent it like this:
Then, no matter whether the person reading your code thinks tabs should be 1 or 8 characters wide, arg1 and arg2 will always line up. Sadly, vim does not have the ability to distinguish marks used for indenting and marks used for alignment and so this has to be done manually.
Re:Keep it simple! (Score:5, Insightful)
the most egregious bug I think I ever introduced was due to code cloning. It was awful. I did not bother to properly refactor (hey it was 12 years ago) and as a result we ended up with diverging clones that needed to be separately maintained.
Correct focus (Score:5, Insightful)
.
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.
Re:Some stuff that was stupid (Score:3, Insightful)
Every compiler made in at least the last two decades has a warning for the same purpose. This type of unnatural ordering of comparisons to force compiler errors where an equals sign is left out usually signifies a code base that is in such a bad state that the developers turn off or ignore compiler warnings.
Re:braces (Score:2, Insightful)
"braces show where code blocks are"
Like I said, "Block scoping is perfectly well indicated by indentation"
You are indenting stuff correctly and consistently right? cause if your not then talking about any other aspect of code formatting is a waste of time.
Re:Keep it simple! (Score:4, Insightful)
The difference between ""cut and paste" friendly code" and "use Cut and paste" is the difference between "bake a nice cake" and "get obese and prone to illness".
Code that is well-factored can be (incidentally) suitable for cut-and-paste, but using cut and paste is the problem.
Re:braces (Score:2, Insightful)
NO! NO NO NO no no no no NO!!!!
You simply do NOT compromise your code for "efficiency" when you are already running a script language. Any web site is extremely scalable, when you grow you just plug in more servers, at some point your database can't handle the load so you start caching your pages, then you add more servers etc.
You never EVER compromise your code for efficiency when you can get 100 times more bang for the buck by adding additional servers.
Re:braces (Score:4, Insightful)
if condition:
statement1
else:
statement2
That's it! No braces at all.
Well, maybe except in dictionaries:
mydict = {"foo": someObject,
"bar": 42,
}
Re:braces (Score:2, Insightful)
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.
No standard is a good standard (Score:3, Insightful)
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.
Re:braces (Score:5, Insightful)
Bollocks.
Draw your line from the closing brace up to the first line with any text on it, that line is the start of your block.
Having your opening braces on an empty line might be more aesthetically pleasing but has zero advantage in making the code clearer.
Either way, the most important thing is to have everyone do it the same way, every time.
Coding standards depend on the ecosystem (Score:4, Insightful)
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...)
Re:braces (Score:2, Insightful)
those who cannot do, write coding standards (Score:1, Insightful)
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.
Re:braces (Score:1, Insightful)
Wow, Whitesmiths style! Afraid if I saw a commit formatted like that the memo wouldn't be very polite. K&R (function braces get newlines) and any of these are fine by me:
A few anti-guidelines (Score:4, Insightful)
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
Re:braces (Score:5, Insightful)
In my short experience in the workin' world, I've come across some pretty spectacularly awful implementations of everything under the sun, from production boxes in shambles to network cables wrapped around sweaty water pipes to 2 year old production code passing GET strings straight to the SQL server unmodified (yay nonprofit sector!), and compromising code for a quick and dirty webpage so I can get things running just a bit faster is 1) the least of my worries and 2) a metric fuckton cheaper than new servers (yay nonprofit sector!).
Let developers work how they want (Score:2, Insightful)
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.
Re:braces (Score:3, Insightful)
Re:braces (Score:4, Insightful)
Idiots who think like this write code that has to run every day, using the previous day's output as input, and takes 28 hours to run.
They think that you can have a baby in one month if you just put more men on the job.
You can't always "put more men on the job", and you want to write code that puts out web pages responsively. Some times algorithms are the key to page performance, and sometimes, it is just coding practice.
Language limitations vs common sense (Score:2, Insightful)
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).
Re:Correct focus (Score:3, Insightful)
I wholly agree, and find that Conway's "Perl Best Practices" does an excellent job of just this, for people who are writing Perl. In the book, Conway goes through a number of different options and describes why they're just bad ideas, arguing mostly from a maintenance and clarity perspective, and cogently suggests superior options.
Re:Some of those examples (Score:2, Insightful)
if your program looks like:
if (sadf ~= /asdfijdfasd/) { ;aiosejfo;saiehnf
dafdijseoifnjseoifjeasdpfjase;oifn
a;seoifnmoeawnfsaoeinf
a;seoifjas;oeinfaef
as;efijesfoijes
} else {
lidnrglsodrnigas
oihjesofnseoanf
}
like the typical perl program, then I can understand
if it's C or C++ then
if (a.is_good()) {
a.modify_with(b);
a.change_for(c);
a.do_something_according_to(d);
} else {
a.report_error();
b.report_unused();
c.report_buggered(d);
}
It is a little less of a sensible rule. Coding standards will be peculiar to each languages idiomatic use.
Just read the classics for the best (Score:2, Insightful)
Linus Torvald Linux Kernel coding style http://lxr.linux.no/linux/Documentation/CodingStyle [linux.no]
Bjarne Stroustrup C++ Style and Technique FAQ (Trivia and style section) http://www.research.att.com/~bs/bs_faq2.html [att.com]
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 [microsoft.com]
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.
Use a proper editor (Score:3, Insightful)
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.
Re:Some of those examples (Score:5, Insightful)
"no NO!! Must not put elses near braces, my precious!" - Larry Wall
I, for one, have never understood Larry's War on Cuddled Elses. It's almost symptomatic of OCD.
Besides, how is the "else" getting "lost?" I mean, it's only two characters from the left margin! Saves lines too.
Maybe it's that I prefer reading source that is not so vertically spread out. The more code and logic on the screen, the better. Density factor.
Re:braces (Score:1, Insightful)
OverflowCount is equally unreadable to xyz124c, you insensitive Micro$oft/Java clod. Use overflow_count instead.
Re:Some of those examples (Score:5, Insightful)
Re:Some of those examples (Score:2, Insightful)
I have a 14" screen on the computer I learned to program on. Extraneous junk on my IDEs took up anywhere from 15%-40% of the screen. As a result, I program concisely. I have an irrational fear of whitespace messing up my code, which results in a love/hate relationship with python.
Also, one thing I've noticed is that when code is written:
if (something){
do_it(x, y, z);
}
The if clause is right above the start of the execution. It feels more solidly 'there' to me, because I see the whole block of code from the 'if' to the '{' as being the opening for the block. I don't see the '{...}' as being a way to force if() to regard the statement as one line, even though that's the case. I know you're supposed to program with lots of whitespace, but I've never liked it.
Re:braces (Score:2, Insightful)
Re:Some of those examples (Score:5, Insightful)
So we have a shop that has a whole lot of perl code and they're sent around this book as well as run perlcritic on our checked in code (which pretty much everyone ignores).
In my couple of years there I've learned a few things.
1) No one can agree on coding standards
2) What people can agree on is so watered down that it's not very useful.
3) The stuff that really causes headaches isn't bad style, it's general insanity. Hardcoded constants and poorly thought out ad-hoc parsers and general brain damage causes a million times more problems than just about anything anyone can describe in a standard.
That said, in my experience the one thing that almost aways saves me time for anything larger than a couple of lines is to use "use strict."
Re:Embedded Coding (Score:3, Insightful)
We do the inverse as far as capitals, but we also use the "static" modifier to make sure nobody tries to call the function from another file.
Re:braces (Score:3, Insightful)
compromising code for a quick and dirty webpage so I can get things running just a bit faster is 1) the least of my worries and 2) a metric fuckton cheaper than new servers (yay nonprofit sector!). :)
So you have several million bucks to pay the damages for a personal information breach.
Then why are you still working as a programmer?
Re:Some of those examples (Score:3, Insightful)
if vertical space is the issue, how about:
if(something_is_true){do_something(); do_one_more_thing();}else{do_something_else();}
That's pretty much what I see when I see open brace immediately trailing an if or else. I prefer open braces to line up with their corresponding close braces.
Re:[Java] Use Checkstyle (Score:1, Insightful)
This is a Really Stupid Post, that I am replying to - a classically stupid post.
1280x1024? I used to work as someone who audited code for a living - I read other peoples' code, cold (their explanations specifically could not be trusted, as we were looking for backdoors and such).
Modularity negatively impacts readibility. You can't just read a module once and presume proper function. You have to carry in at least, example data from each reference to that function. In one case, we determined that a particular malformed date would allow someone to adjust their own balance. The date could not pass the web page audits, but could be driven in from a tool that could force arbitrary data into the post stream. Testers didn't find it because they were testing externals (i.e., web pages).
It was almost impossible to find the interaction that allowed the balance adjustment, and it was heavily obscured by the use of modularity and objects. The coders had standards that had said that they could only have routines that were about the size of a page.
So control flow jumped from routine to routine, and there were some routines that were split because they were doing complicated things, edits and stuff, that were too large to put into simple routines. Things that were data relative were pushed into data objects, and this just served to further obfuscate the situation-and slow the code.
They would have benefited from longer pages, functionally sized modules, and standards that served them, ratherbthan vice versa.
What they had was a rat's nest of modules and methods that met all their code standards and in which backdoors could be hidden, and it was impossible to say whether the backdoors were intentional or not.
Re:Some of those examples (Score:3, Insightful)
The Most Important Rule (Score:4, Insightful)
Re:braces (Score:2, Insightful)
In which case, let me give you the benefit of my experience as well, the GP poster is absolutely correct.
Its a funny thing, but *every* junior developer (which I define as All significant performance problems in software are architectural in nature.
You should be coding in the most easy to maintain style. Doing something difficult to maintain (like breaking MVC by merging controller logic into the view) might save a few milliseconds here and there. You will be quite proud of this until someone with more experience comes along and drops in a second level cache or adds some database indexes and increases performances by two orders of magnitude.
Re:braces (Score:4, Insightful)
I am really sorry, something else you can learn from me is to always use the preview button :).
The preamble was a little bit of waffle anyway... the important point...
All significant performance problems in software are architectural in nature.
You should be coding in the most easy to maintain style. Doing something difficult to maintain (like breaking MVC by merging controller logic into the view) might save a few milliseconds here and there. You will be quite proud of this until someone with more experience comes along and drops in a second level cache or adds some database indexes and increases performances by two orders of magnitude.
Re:Some of those examples (Score:5, Insightful)
Density is the opposite of readable and maintainable. One of the main aspects of maintainable code is being able to find and change a single line of code quickly and without having to worry about breaking other nearby lines. Having more code per line means it takes that little bit longer to find and is that little bit riskier to change the one line of code. "Lost" in this case is only a minor delay, but when you add that delay up across several thousand bugs (i.e. any project in the Real World), it means you are wasting your time tracking down bugs in dense code rather than adding new features or working on other projects.
Pop quiz: find and remove the bracketed clause in the above paragraph. Then think about how much faster you would have done that if it had been on its own line. Then think about how much faster you could have done that to 100 different paragraphs. It may not make a difference on the projects you work on, but in something the size of a perl interpreter or a web browser, it makes a huge difference.
Coding standards are stupid, better to localize (Score:3, Insightful)
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.
Re:Some of those examples (Score:4, Insightful)
I find that tracing parenthesis is a lot easier.
Re:Some of those examples (Score:5, Insightful)
Bollocks. It's a tradeoff just like every other debate in the programming world. Sure, Perl gives you the ability to put way to much code on a single line. But the opposite problem of putting loads of white space all over the place is almost as bad.
The more you spread out the code, the more you have to scroll. White space is valuable when it means something, like to separate discrete tasks within a long function. But the whole
}
else {
thing is just a waste of space. It's one line less of code I can see. I visually parse } else { instantaneously. Similarly, some compound expressions or chained method calls make perfect sense. The right place to break out multiple lines depends on the reader's own cognitive abilities and familiarity with the symbols being manipulated.
Otherwise
writing
like
this
would
be
much
easier
to
read
log servers instead of printfs (Score:3, Insightful)
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.
Re:Some of those examples (Score:2, Insightful)
Re:Some of those examples (Score:3, Insightful)
I think that having the opening brace on one line makes the block easier to identify as the conditional/method name/etc. looks similar to code; as my parse speed sometimes lags behing my reading speed I might overlook the beginning of an oddly-indented block. The additional linebreak is no problem because modern mice have scroll wheels and keeping long methods in mind is what short-term memory is for. That works well for me, but I have better short-term memory than most people.
For you, keeping as much memory free as possible is more important than being able to identify a block without having to parse a line. Fine for you, but not universally superior.
Most of these holy wars continue only because people forget that not everyone is the same and different people have different requirements. As in most cases there is no one-size-fits-all solution.
Re:Some of those examples (Score:5, Insightful)
My dear Doctor, readability metrics boil down to personal tastes - subjective, in other words. While perhaps what you choose is even the preference of the majority of coders, it's not mine.
Advocating for braces and the negatory conjunctive "else" on the same line is not the same as "having more code per line," e.g. more than one statement per line.
In the responses to the OP, we've if/else on three lines-
if (...) {
...
...
...
...
} else {
}
-and six lines-
if (...)
{
}
else
{
}
Whilst reading six lines is not a problem for me, I prefer the three line variant, as it means less scrolling over slow ssh connections. Thank goodness we have automagic reformatting IDEs for those who won't accept other formats.
However -- it is a sorry state of affairs that on /. the replies to an enquiry about "coding standards" end up focusing on code formatting... I'd much rather have been debating architectural design patterns as the response to "coding standards."
Positions on design patterns, over the last few years, appear to have accreted into two clusters, those for and those against. I am one of those in the "for" camp, where learning the whys and wherefores of a particular set of data structures and classes, and behaviors arising from said structures, determine architecture.
Those "against" appear, to my reading, to be willing to forgo such learning and accept whatever baked-in design patterns the platform's designers chose.
Now, on the one hand, I accept that that's the case, as there is an observable stratification of programming ability existing in the world of software developers. One most go with one's strengths, and not everyone is suited to solving the issues architecture.
On the other hand, if a developer is so inclined, there is still plenty of latitude available when structuring applications.
Finally, there appears to have been a rise in the strongly anti-design patterns camp - the learning and applying thereof, that is. Most particularly, the anti-Java, pro-Ruby/RoR camp, where seemingly one must accept the baked-in design patterns chosen by the platform's architect, without variation.
A direct descendent of that camp, the adherents to the prototype.js and scriptaculous libraries, accept the original author's patterns to the point where performance deficits due to overuse of lambda functions are not only accepted, they are ignored.
That, IMNSHO, is sad comment on the state of software development. Productivity over performance is an awkward choice, to say the least.
Re:Some of those examples (Score:5, Insightful)
Re:Some of those examples (Score:3, Insightful)
I would strongly suggest that you do the following instead:
The reason being that I can look at either the start or the end brace, and simultaneously see the matching brace without having to scan sideways or otherwise dig through extra code. Or if I wanted to change the else to an elseif, I could just move to the end of that line start typing, without worrying about having to go back 2 characters or otherwise avoid clobbering the brace.
To take the example further, let's say the block originally looked like:
And Joe Newbie changes it to:
Spot the bug. Putting the braces on their own lines prevents this sort of stupid mistake (and it *is* stupid, I agree, but it is also common). Sure, it's not that hard to find/fix once you hit compile, but wouldn't you rather be spending your time tracking down the interesting bugs than dealing with stupid bugs like this?
Re:Some of those examples (Score:1, Insightful)
A common mistake I have seen programmers make is removing a branch from an if-else statement.
if {
} else {
}
With the above format it is very easy to accidentally remove the brace preceeding the "else" when removing the else branch.
if {
}
else {
}
With this coding style it is less prone to disastrous pruning.
Re:Some of those examples (Score:5, Insightful)
I've been a professional developer for 8 years and I've never spent significant time dealing with that bug. I'd rather have the code consistent than have it one way or the other. Developers have strong feelings about these things because of our attention to detail. But the sign of a good programmer is being able to say, "It's not worth my time to even think about this". If it was a clear win one way or the other then of course I'd get on board. But it's not. Being able to see more code on one screen has value.
Re:Some of those examples (Score:2, Insightful)
>Density is the opposite of readable and maintainable.
Children's books, aimed at a young comprehension level, are written with 8 or 10 words per page.
Do you prefer this format to one aimed at a higher level of comprehension?
Here is your argument for "density" then.
Re:Some of those examples (Score:3, Insightful)
Density shmensity.
if( denotes the beginning of the conditional
} denotes the end
} else means it continues instead of ending
So.
// begin ... // do stuff // end // what? ... // uhm // end again?
if(...){
}
else{
}
Confusing! What's that dangling else doing there? Sure looks funny without its friend the }.
Those arguing in favor of braces on their own lines are usually obsessed by this kind of non-issue. They write like this:
... ... ...
if
(
)
{
}
else
{
}
Which is even less readable.
Now every person is different and sees things differently. I find it useful to put empty lines between sets of unrelated code, just for the very reasons you cite for putting } on its own line. Some people criticize that practice for a variety of reasons, but it works well for *me* and makes it easy for *me* to find what I need to find quickly. I happen to think it makes the code clean and maintainable, just as I think that } else { does.
JAPH.