Beta

×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Best and Worst Coding Standards?

Soulskill posted about 6 years ago | from the buffer-overrun dept.

Programming 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?"

cancel ×

956 comments

Sorry! There are no comments related to the filter you selected.

Some of those examples (4, Funny)

AndGodSed (968378) | about 6 years ago | (#24261601)

Sound an awful lot like coding in C... no bad coding practice needed...

Keep it simple! (0, Insightful)

Anonymous Coward | about 6 years ago | (#24261641)

Make it "cut and paste" friendly, and as small as possible.

Re:Keep it simple! (5, Insightful)

bondsbw (888959) | about 6 years ago | (#24261771)

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:Keep it simple! (4, Insightful)

superid (46543) | about 6 years ago | (#24261923)

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.

Re:Keep it simple! (4, Informative)

StrawberryFrog (67065) | about 6 years ago | (#24261947)

There are several tools that can detect cut and paste code:

Simian: http://www.redhillconsulting.com.au/products/simian/ [redhillconsulting.com.au]
PMD: http://pmd.sourceforge.net/ [sourceforge.net]
DuplicateFinder: http://www.codeplex.com/DuplicateFinder [codeplex.com]

And probably others

Re:Keep it simple! (5, Funny)

4D6963 (933028) | about 6 years ago | (#24261957)

Make it "cut and paste" friendly, and as small as possible.

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

Wait.. are you trying to say that copying the same lines of code over and over again must be avoided? So tell me genius, how else would you implement such a function without copying?

int multiply(int a, int b)
{
int x=0;

if (a==1)
{
x+=b;
}

if (a==2)
{
x+=b;
x+=b;
}

if (a==3)
{
x+=b;
x+=b;
x+=b;
}

// Damn lameness filter, wouldn't let me paste my code in the entirety of its 132,356 lines

return x;
}

Re:Keep it simple! (3, Insightful)

StrawberryFrog (67065) | about 6 years ago | (#24261971)

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.

Space Usage (4, Interesting)

Nerdfest (867930) | about 6 years ago | (#24261647)

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.

braces (3, Interesting)

SKiRgE (411560) | about 6 years ago | (#24261653)

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

Re:braces (1)

paradxum (67051) | about 6 years ago | (#24261673)

I honestly agree with that for most code. The only exception is when using php for simple page area selection such as:

blah blah blah html
<? if($something){ ?>
more html
<? } else { ?>
some other html
<? } ?>
end/footer html

but rules were made to be broken right?

Re:braces (3, Insightful)

Splab (574204) | about 6 years ago | (#24261709)

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

Re:braces (2, Insightful)

Anonymous Coward | about 6 years ago | (#24261857)

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.

Re:braces (4, Interesting)

Southpaw018 (793465) | about 6 years ago | (#24261863)

That kind of code, when using PHP for templating, can make things much more efficient server side. Remember that anything within PHP tags is parsed by PHP. On a high volume site, even the relatively minuscule difference between passing something straight to the browser and echo("something"); can make a big difference in speed and resources.

Besides, this is what syntax highlighters were made for. There are very good free ones on every single platform for a reason :p

Re:braces (2, Insightful)

Splab (574204) | about 6 years ago | (#24262005)

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 (5, Funny)

fictionpuss (1136565) | about 6 years ago | (#24261875)

True - but at least it keeps thousands of otherwise dangerous PHP developers safely occupied.

Re:braces (1)

kauos (1168299) | about 6 years ago | (#24261909)

In practice debugging html templates with integrated jsp/php code (I started as a JSP developer) is not really that much harder than debugging straight java code. Its just what you're used to. And in fact for a LOT of smaller web applications it is the quickest, simplest and easiest way to get the job done. I think you're being a bit harsh knocking the use of conditional PHP statements in html code.

Re:braces (1)

guycouch (763243) | about 6 years ago | (#24261867)

Try this: blah blah blah html more html some other html end/footer html

Re:braces (1)

guycouch (763243) | about 6 years ago | (#24261879)

... maybe I should try the preview button.

blah blah blah html
<? if($something): ?>
more html
<? else: ?>
some other html
<? endif; ?>
end/footer html

Re:braces (-1, Flamebait)

Anonymous Coward | about 6 years ago | (#24261675)

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

That Sir, is because you are a twat.

Re:braces (1)

kauos (1168299) | about 6 years ago | (#24261693)

I agree! It annoys the crap out of me too. In theory the reason is so that when you hotkey (Vim : Shift+5) from the close brace to the open brace, you don't have to move one more line up to see the condition statement. But in all honesty I just don't notice that as an issue. Its more important to have nicely laid out code (ie open brace on a new line), rather than have the hotkey work more efficiently.

Re:braces (0)

Anonymous Coward | about 6 years ago | (#24261853)

Dont you mean %? % has been working in vi, ex and other editors for close to 30 years.
Do you still use wq! when x! has been doing the same thing for every version of vi for at least 25 years too?
x! is not ambiguous but does wq! mean (w)q! or w!q?

Re:braces (1)

Hermel (958089) | about 6 years ago | (#24261697)

Why? Is there a 'better' alternative?

Re:braces (3, Informative)

SKiRgE (411560) | about 6 years ago | (#24261715)

yes, putting the else on a new line makes it a bit more readable; you know that line marks the beginning of an else:

if( condition ) {
    statement1;
}
else {
    statement2;
}

reading this kind of code tells you that there is an else condition there. having a leading closing brace makes you have to read into the line to see what's going on. I know it's 2 characters, but when scanning code for structure, it helps to have it on a bew line.

Re:braces (1, Interesting)

thogard (43403) | about 6 years ago | (#24261775)

That depends on how you parse the closing }. I have no problem wrapping my head around if foo then stuff else other stuff. I don't need it to sick out with extra special formatting.
Most people have an innate basic built in "light" ignore for it since it doesn't matter unless your focusing on the statement lists after the else.
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.

Re:braces (3, Insightful)

SKiRgE (411560) | about 6 years ago | (#24261807)

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 (2, Insightful)

thogard (43403) | about 6 years ago | (#24262045)

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.

Re:braces (5, Interesting)

fictionpuss (1136565) | about 6 years ago | (#24261829)

Well, as long as we're admitting that "readable" is an entirely subjective experience.. I'd have to say that I would find that notation less intuitive than the "} else {" construct.

It's too similar to consecutive 'if' statements which of course, breaks the logic.

Also, extending your notation logic fully results in:

if ( condition )
{
        statement1;
}
else
{
        statement2;
}

Which, although a waste of lines, is less confusing than your example.

Re:braces (1)

SKiRgE (411560) | about 6 years ago | (#24261851)

that's actually how I code in c++. keeping the opening braces with the opening statement is how I code in Java. both ways have to do with the coding standards where I work.

Re:braces (5, Insightful)

TheRaven64 (641858) | about 6 years ago | (#24261921)

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:

{tab}function(arg1,
{tab}_________arg2,

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:braces (5, Interesting)

Glonoinha (587375) | about 6 years ago | (#24261963)

Ding ding ding - we have a winner.
Real coders write code that you can take a ruler from any given close brace and draw a vertical line right up to the matching open brace, every time. Everybody else gets fired.

Lines are cheap. Time added trying to figure out an obfuscated code structure because somebody wanted to save lines (ie, put the open brace on the same line instead of doing the above) is expensive.

Re:braces (4, Interesting)

gfxguy (98788) | about 6 years ago | (#24262057)

That's the way I've always done it, but it seems like most published coding standards don't like it.

To reiterate: matching braces should line up horizontally AND vertically. It may "waste" lines, but the code is a lot more clear.

I also, except in some cases (like some class getter/setter methods, where they're just all one after each other and it's obvious what they are), use braces even if it's a single statement that's being executed within. I don't see why code should be inconsistent just because it's a single statement that's being executed.

I often get berated by other programmers for that style, but the only time I've applied for a job and had to stand at a white board and write code, and then describe my coding style, they seemed to appreciate it.

Re:braces (0)

Anonymous Coward | about 6 years ago | (#24262071)

I prefer:

if (exp) {
} else {
} ...but working at a place which has hundreds of branchs under version control they came to the standard:

if (exp)
{
}
else
{
} ...in order to cut down on merge errors. It makes a lot of sense in their situation, but I'll stick with the former for my own projects - I'd rather see more lines of code.

Re:braces (3, Interesting)

Anonymous Coward | about 6 years ago | (#24261905)

That formatting doesn't follow the structure of the code. The else is not a new instruction, but a continuation of the if. It is "if condition instruction else instruction", not "if condition instruction" followed by "else instruction".

An argument may be made for always putting braces on separate lines, but if you put opening braces on one line with the instruction, then the instruction should continue on the same line as the closing brace too.

Re:braces (2, Insightful)

LEMONedIScream (1111839) | about 6 years ago | (#24261773)

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 (5, Interesting)

Dionysus (12737) | about 6 years ago | (#24261717)

If Kernighan, Ritchie [wikipedia.org] , and Torvalds [linux.no] does it like that, who am I to do differently.

Re:braces (3, Insightful)

DaveV1.0 (203135) | about 6 years ago | (#24261811)

Not them, and that is a good enough reason.

Re:braces (4, Interesting)

tolomea (1026104) | about 6 years ago | (#24261741)

I really don't get this obsession people have with putting braces on separate lines.

Block scoping is perfectly well indicated by indentation and blank lines are valuable for dividing functional blocks of code.

When you go and put all the braces on separate lines it totally kills the visual effect of the actually empty lines. Then you'll have to go and start using multiple blank lines for separating things and before long half the screen will be empty and mostly empty lines.

Hmmm perhaps that's it, maybe this is a scheme for people who don't like looking at the code.

Re:braces (2, Insightful)

SKiRgE (411560) | about 6 years ago | (#24261791)

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 (4, Insightful)

thogard (43403) | about 6 years ago | (#24261817)

The code is important. The braces are syntactical sugar.

Re:braces (3, Insightful)

SKiRgE (411560) | about 6 years ago | (#24261837)

yes the code is important, but knowing what code gets grouped and being able to follow the flow is just as important.

Re:braces (1)

thogard (43403) | about 6 years ago | (#24261979)

And according to the parser, that has nothing to do with the indenting, line spacing or in some cases the curly braces. My take on a code is it has to be understood at several levels and one of those is a higher level where such things are trivial all the way down to knowing that the sub brace has been added so they can put a extra variable on the stack. Remember in C the {} does mean "create a new stack frame" as well as grouping.

Re:braces (2, Insightful)

tolomea (1026104) | about 6 years ago | (#24261961)

"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:braces (2, Interesting)

TheRaven64 (641858) | about 6 years ago | (#24261935)

Maybe the way you code, you never have a line that is so long that it needs to be broken. In most C code I've seen (and all C++ or Java code) a lot of lines exceed the 80-column width that is a common maximum for coding conventions. You then can't clearly distinguish between the start of a block and a wrapped line without clearly inspecting the indenting. This is even more true in Objective-C, where long methods are often written with one parameter on a line.

Re:braces (5, Insightful)

heffrey (229704) | about 6 years ago | (#24261749)

It doesn't really matter what you do, so long as everyone on the team does the same thing.

Re:braces (4, Interesting)

Dachannien (617929) | about 6 years ago | (#24261761)

I don't like seeing opening braces sharing a line with anything else at all, unless the block gets closed on the same line.


if(something)
    {
    do_something();
    }
else
    {
    do_something_else();
    }

Yeah, it takes a bit more space, but I find it a lot easier to match blocks up when the braces are indented the same amount.

Re:braces (4, Interesting)

SKiRgE (411560) | about 6 years ago | (#24261819)

I keep braces on their own line when coding c++, but I do my indentation differently:

if(something)
{
    do_something();
}
else
{
    do_something_else();
}

Re:braces (3, Insightful)

DaveV1.0 (203135) | about 6 years ago | (#24261845)

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

Anonymous Coward | about 6 years ago | (#24261977)

This is the only one of the styles which would actually drive me insane.  Still probably let it go if it was consistent and worked

Most styles in the style war want the braces in the outer scope thus I expect one of the following:

//my typical style, empty line above if (or this comment line if included) and after else's '}'
//to partition from the main block
if(isValid){
    statement;
}
else{
    statement;
}

//Other styles I will read without questioning the coder's style:

//fully written out
if(isValid)
{
    statement;
}
else
{
    statement;
}

//else in brackets
if(isValid){
    statement;
} else {
    statement;
}

//mix match (I'd assume more than one person however.. or blindly copied code and
//risk of bugs)
if(isValid)
{
    statement;
} else {
    statement;
}

...

the things I will hand you back the code for unread if I can:

//wrong tab depth
statement
    statement

//double close
else{
    list of statements;
}
}

//missed indent
if(isValid){
statement

Re:braces (1)

elronxenu (117773) | about 6 years ago | (#24261827)

I can't stand seeing 'if' with no whitespace before the opening parenthesis, as in 'if(condition)'.

'if' is not a function! (at least not in perl nor C).

Re:braces (1)

SKiRgE (411560) | about 6 years ago | (#24261873)

and that's a completely valid point. I'm saying I don't like seeing braces a certain way, just as you don't like the spacing with conditional statements a certain way. I never said anywhere that one was right or wrong, just I personally don't like seeing it one particular way.

Re:braces (0)

thogard (43403) | about 6 years ago | (#24262011)

if is functional in C and it always has been.
if(foo) gets reduced to "test(foo)" followed by a "jump if NE" in most cases with nearly every CPU out there.

Re:braces (1)

tolomea (1026104) | about 6 years ago | (#24262021)

It scares me to think that you need to have the whitespace indicate this fact to you.

The syntax highlighting, presence of braces and presence of an extra level of indentation on the next line don't cover it?

By the way, sizeof, not a function either, it's actually an operator, but I'm willing to bet that you'd object strongly to writing "sizeof(bob)" as "sizeof bob".

Re:braces (0)

Anonymous Coward | about 6 years ago | (#24261847)

And it drives me nutters to see it the other way.

if( condition ) {
        statement;
}
else {
        do something else;
}

so ... probably is personal preference too.

GNU Indent (3, Insightful)

Jim Hall (2985) | about 6 years ago | (#24261861)

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:GNU Indent (1)

SKiRgE (411560) | about 6 years ago | (#24261899)

yeah, I love the formatter in Eclipse. I just match it up to the company's coding standards, and (try to remember to) run the formatter before I check in my work too.

Re:braces (3, Insightful)

harry666t (1062422) | about 6 years ago | (#24262023)

Braces, braces, braces... I code in Python, which seems to be the only computer language that got the braces right:

if condition:
    statement1
else:
    statement2

That's it! No braces at all.

Well, maybe except in dictionaries:
mydict = {"foo": someObject,
          "bar": 42,
          }

JSF (Lightning II) coding standards (5, Interesting)

PsyQo (1020321) | about 6 years ago | (#24261671)

I've always found the Joint Strike Fighter's coding standards document an interesting read. It is available from Bjarne Stroustrup's website [att.com] (pdf)

Re:JSF (Lightning II) coding standards (0)

Anonymous Coward | about 6 years ago | (#24261783)

Nice read. It's not unreasonable. About the only thing I can't stand is braces on separate lines, preferring:

if( flag ) {
        salute();
}

But that's just me :-)

Re:JSF (Lightning II) coding standards (-1, Offtopic)

Anonymous Coward | about 6 years ago | (#24261843)

I've found penthouse forums to be an interesting read as well.

Re:JSF (Lightning II) coding standards (0)

Anonymous Coward | about 6 years ago | (#24261895)

Name and address withheld.

Serious != good (4, Interesting)

Exanon (1277926) | about 6 years ago | (#24261681)

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

It's easy (5, Funny)

krkhan (1071096) | about 6 years ago | (#24261707)

First off, I'd suggest printing out a copy of the /. comments, and NOT read it. Burn them, it's a great symbolic gesture.

Well hungarian notation... (2, Insightful)

Anonymous Coward | about 6 years ago | (#24261711)

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:Well hungarian notation... (3, Interesting)

Lucas.Langa (922843) | about 6 years ago | (#24261903)

Also found I prefix in .NET really bad pracitce for marking interfaces like ICollection, what about when You decide turn interface to abstract class?..

Well. The whole point of having interfaces is allowing the implementation of a certain method set to the world, which later can be used in your APIs using polymorphism. If you later decide to break the contract and make an interface a class, then probably a name change (made also automatically in tools like Eclipse or NetBeans) won't be any worse.

As for the Hungarian notation, the standard form is indeed worthless. But we tend to use simple maximum three letter abbreviations of Swing components, to know that we are taking the username from txtLogin and listening for pressing btnOK. Code is more often read than written and this quasi-Hungarian style actually works pretty well.

In fact, having interfaces named like "IPasswordProvider" is something very similar. It enables easy reading of your code and when you want to make a change, you instantly see that this type is an interface, therefore you cannot instantiate it directly, but you can implement this interface in any arbitrary class you may already have written, etc. Plus, Sun coding standards encourage you to name interfaces in a passive adjective way like "Serializable", "Comparable", etc. To comply with this format is not very natural for interfaces like "IPasswordProvider" or "IModelContext".

Re:Well hungarian notation... (0)

Anonymous Coward | about 6 years ago | (#24262037)

"Well hung"..huh huh...

Re:Well hungarian notation... (1)

StrawberryFrog (67065) | about 6 years ago | (#24262049)

Also found I prefix in .NET really bad practice for marking interfaces like ICollection, what about when You decide turn interface to abstract class?..

You rename it.

Is this common for you? Tell me the last time that it was a "really bad" problem. It's not common for me. In fact the only similar refactoring that I've ever seen used is the opposite: to extract an interface from a class.

An interface is different to an abstract base class; an interface doesn't determine the base class heritage. If you make that kind of change, you should also be prepared to rename the interface/class.

Re:Well hungarian notation... (2, Informative)

Anonymous Coward | about 6 years ago | (#24262051)

wParam

You were doing it wrong [gregleg.com] . The compiler knows it's a fucking word or long int or whatever, use the prefixes to encode something the compiler DOESN'T know about.

My new standard (4, Interesting)

thogard (43403) | about 6 years ago | (#24261729)

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.

Re:My new standard (1)

4D6963 (933028) | about 6 years ago | (#24261835)

That quote isn't a rule to remember, it's just a basic fact. How does remembering that help a project avoid running into problems, and most importantly, do you even understand what a coding standard is?

Re:My new standard (2, Insightful)

Southpaw018 (793465) | about 6 years ago | (#24261901)

Though this is technically OT, I think he's trying to restrict development to those elements. Alas, the real world doesn't quite work like that, what with office politics and policies and bosses and humans being, you know, humans.

Re:My new standard (1)

thogard (43403) | about 6 years ago | (#24261931)

Because what you might call a coding standard describing how to format a line of code just happens to be a trivially small piece of the pie. The core involves design and implementation details. I look at so many projects today that are never done. They all comes from a lack of understanding the basics. We tend to throw new languages at problems in an effort to solve the real problems yet more and more projects are late, over budget and never fully complete. My core coding standard is "write it in a language where it can be finished" which is knocking out more and more of the trendy languages since you can't complete a project if its core run time keeps changing. I have written a number of programs that are done. They don't get updated, they don't need to since they just keep meeting their requirements decade after decade yet statement formatting wasn't a major issue with most of them and the ones that it did were languages that predate the free form concepts like FORTRAN on punch cards.

Enforcing dependencies with coding std.. (0)

Anonymous Coward | about 6 years ago | (#24261747)

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.

[Java] Use Checkstyle (5, Informative)

Lucas.Langa (922843) | about 6 years ago | (#24261751)

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:

  • limit the length of the method to be visible on one 1280x1024 screen; if it's longer it's probably handy to extract smaller methods from it - which will be far more easy to read
  • similarly: set a file length limit (e.g. 1000 lines should be enough for everybody)
  • an upper limit on the allowed number of method parameters seems to be a good idea as well
  • ensure that new code is commented by marking structures which could be javadoced but aren't
  • any naming and formatting convention is better than no convention; Checkstyle can use regular expressions to validate type, variable and other names. It can also check for whitespace constraints, new lines, etc.
  • avoid star, redundant and unused imports
  • enforce or forbid the usage of the tabulator character to have all code clean no matter where you open it
  • warn on redundant modifiers
  • enforce the usage of braces everywhere (e.g. disallow if (something) action; ): no misformatting will hide a trivial but dangerous bug
  • a major one: Checkstyle can warn if it discovers a typical coding problem (of course this has some false positives but better to be on the safe side): double checked locking, lack of hashcode when overriding equals, switch fallthroughs, illegal catches and throws, lack of super.clone() or super.finalize(), etc.
  • you can also constraint the number of returns from methods (we found it to be very useful to set this to 1, using a result variable everywhere else - it's far easier to get hold of the code flow then)
  • we also constraint the if depth and boolean expression complexity to manage the cyclomatic complexity - also for easier reading
  • it's useful to make Eclipse clean up your code on every save: to add "final" where it can, to fix imports, format the code to the specified form, etc.

Of course, we let developers to add suppresions for the 1% of false positives. In fact, there are very few suppresion rules set.

Re:[Java] Use Checkstyle (0)

Anonymous Coward | about 6 years ago | (#24261849)

Huh, I never realized the SS used java.

Re:[Java] Use Checkstyle (0)

Anonymous Coward | about 6 years ago | (#24261987)

Even here you see why people hate coding standards.

avoid star, redundant and unused imports

This only impacts build time. Not worth the time and hassle of importing every class individually for saving an additional 90 seconds on the rare occasion you do a complete rebuild.

enforce the usage of braces everywhere (e.g. disallow if (something) action; ): no misformatting will hide a trivial but dangerous bug

Stupid, forcing braces makes some code more unreadable. Situations where it's inappropriate to omit them can be caught during code review.

The best coding standard is... (1, Funny)

Anonymous Coward | about 6 years ago | (#24261763)

the one that follows the code I write. Every other standard is crap.

developer buy-in (4, Insightful)

Dionysus (12737) | about 6 years ago | (#24261765)

Without developer buy-in, whatever coding standards you come up with will be useless. IOW, ask your developers to create the standard together.

Re:developer buy-in (5, Funny)

Minwee (522556) | about 6 years ago | (#24261815)

ask your developers to create the standard together.

Why don't you just give them all giant Q-tips and play the Star Trek fight music every time they meet?

Surely that would be at least as productive as asking them to all agree on coding standards.

Re:developer buy-in (1)

JaredOfEuropa (526365) | about 6 years ago | (#24261955)

IOW, ask your developers to create the standard together.

Better order a cage and have a few medics standing by for the inevitable K&R vs. ANSI style deathmatch.

Coding standards should not optional, and you can and should enforce them. Just make sure that they are reasonable (i.e. not too loose nor to strict), make sense, and are the same across your organisation (don't let every project have their own standards). If a developer has a reasonable objection to parts of the coding standards, then it's worth listening to him and consider changes the standard, but if he refuses to apply the standard because he disagrees with some of its rules, then he's off the team.

JSF Standards (0, Redundant)

OneMadMuppet (1329291) | about 6 years ago | (#24261805)

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.

precise spacing (3, Interesting)

griffjon (14945) | about 6 years ago | (#24261821)

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.

Re:precise spacing (1)

TheRaven64 (641858) | about 6 years ago | (#24261953)

Sounds like the coding standards were written by a Fortran developer, or the person was actually writing Fortran and didn't understand the difference between the language and the coding standards.

Hungarian notation (1)

yanyan (302849) | about 6 years ago | (#24261831)

Hungarian notation. Ugly.

Some stuff that was stupid (1)

sconeu (64226) | about 6 years ago | (#24261915)

  1. You will put spaces around every parenthesis
  2. You will use braces for every conditional, even if it's one line
  3. You will put the constant on the left for comparisons. This one isn't bad in and of itself, it's an =/== fix, but combine with...
  4. You will always have a comparison, EVEN FOR BOOLEANS [i.e. if ( TRUE == someVal )]

Re:Some stuff that was stupid (2, Insightful)

jrumney (197329) | about 6 years ago | (#24261949)

3. You will put the constant on the left for comparisons. This one isn't bad in and of itself, it's an =/== fix...

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:Some stuff that was stupid (0)

Anonymous Coward | about 6 years ago | (#24262043)

"if ( TRUE == someVal )" does not mean the same as "if ( someVal )". If you must use this style then write "if ( FALSE != someVal )".

Worst (1, Interesting)

Anonymous Coward | about 6 years ago | (#24261919)

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.

badness abounds in visual basic (5, Interesting)

hucke (55628) | about 6 years ago | (#24261927)

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 this tool. Every company has coding standards, and you're going to have to learn that, and work with it."

I did the best I could, but the thing was still a piece of crap. I finished up the part of it that I had agreed to do (the standalone communications piece that would copy MS-Access files over a modem), offered a bit of advice where I could about the main program, but then moved on to other projects.

The POS project still wasn't working reliably, a year after the promised delivery date, and several hundred thousand dollars over budget. The customer was furious, as they were running the thing in production, and every time the database disappeared some manager would have to drive out to various shops with backup tapes, then spend hours on the phone with the programmers. Within a year, the company was gone; the founders split up, one made a clean getaway, the other sold the remnants (i.e., the programmers and the client list) to another Microsoft-centric consulting company.

Re:badness abounds in visual basic (4, Funny)

Splab (574204) | about 6 years ago | (#24262025)

I love abbreviations, not being native English speaker I used to think POS was "piece of shit" since its usually being used when talking about software (failed software).

(Or the always common "IANAL", well good for you buddy, but we are talking about legal issues here - the arse pounding is for when you get behind bars)

Correct focus (5, Insightful)

QuietLagoon (813062) | about 6 years ago | (#24261937)

What standards have you found worked well in practice, increasing code readability and maintainability?

.

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.

Embedded Coding (4, Interesting)

JPEWdev (770760) | about 6 years ago | (#24261945)

I write code for embedded systems where there are many hundreds of C files that all need to compile together to form a single executable (everything shares a single address space). Since there are alot of modules working together, the most useful thing is the usage of prefixes for modules components. For example, all of the database public methods, defines, etc. are prefixed with a DB_ and all the private ones are prefixed with a db_. Granted, it is up to the programmer to enforce these restrictions, but it is nice to be able to tell exactly where a function comes from when reading through some else's code.

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.

As long as the bosses remember that... (1)

itsdapead (734413) | about 6 years ago | (#24261967)

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

should use software to enforce standards (1)

petes_PoV (912422) | about 6 years ago | (#24261973)

Most places I've worked that have emploted coding standard require the code to be "eyeballed" in order to enforce them. While this is adequate when a project starts out and there are o time pressures, the standards tend to lapse as deadlines approach. No manager is his/her right mind wants to be the person who delays a project and certainly not because the code isn't indented properly.

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.

Secure Coding Standards (1, Informative)

Anonymous Coward | about 6 years ago | (#24261989)

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

Code reviews required before checkin (0)

Anonymous Coward | about 6 years ago | (#24261993)

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.

Goto's can be useful (1)

theblondebrunette (1315661) | about 6 years ago | (#24261999)

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.

Simple standards are best (1)

Ceallach (24667) | about 6 years ago | (#24262003)

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.

K&R (1, Troll)

bugi (8479) | about 6 years ago | (#24262015)

K&R style is all you ever really need.

Standards have to be grown (1)

russellh (547685) | about 6 years ago | (#24262041)

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.

No standard is a good standard (2, Insightful)

khendron (225184) | about 6 years ago | (#24262069)

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.

Load More Comments
Slashdot Login

Need an Account?

Forgot your password?
or Connect with...

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>