I'm sure that you know what I'm talking about. I call it coding style (cause I don't know what it's called). But whatever we call it, is it good or bad? Does encouraging it have an effect of higher productivity of developers? Should we ask developers to try to write code the way we tell them, so to make the whole system become style-consistent?

I was actually coming here to ask a very similar question just now - when automatic code formatting tools are available and convenient, is it more important for those tools to not be run (and preserve inconsistent personal styles) or to have a style enforced?
–
fluffySep 13 '11 at 22:21

14 Answers
14

A coding standards document is useful. It's most useful when it's short enough that anybody can remember the whole thing without too much trouble and when it doesn't cause anybody too much pain.

How you choose to indent code in your organization, or capitalize names, or implement your loops, or comment your code doesn't matter all that much; the helpful part is getting everybody to write code that looks about the same as everybody else's.

It avoids having to spend a minute recalibrating your expectation of where braces should be and such every single time you look at someone else's code.

It avoids having several different styles of code all in the same file.

Perhaps most importantly, having a written standard avoids arguments about coding practices during code reviews.

Again, what the standards are doesn't matter as much as having some sort of simple, straightforward standard. So, put all your developers in a room and let them argue about what the standards should be. This meeting could go on indefinitely, so the rules are:

Anything not decided by the end of the meeting will be decided by the manager.

The meeting will end after two hours, or when someone starts shouting or crying, whichever comes first.

The entire standard will fit (in reasonable type size!) on a sheet or two of paper, double-sided only if absolutely necessary.

Consider adopting somebody | else's | standards either as a starting point for your own coding standards meeting, or as a way of avoiding the meeting entirely.

Once agreed upon, developers should be able to (and should be expected to) police themselves. Occasional deviation from the standard shouldn't be a big deal (and might even be justifiable), but curmudgeonly refusal to abandon some favorite personal style in favor of the standard should result in immediate relocation to the office with the leaky water pipes, or whatever.

Demian Brecht points to lint tools. These are a perfect complement to a coding standards document. It's merely good to stick to coding style standards; it's important to stick to coding standards that relate to dangerous practices. Nobody other than the author is going to check that every line of code meets the standard for style, but you should certainly consider building a lint tool into your team's workflow to automatically catch likely bugs. In addition, the tool itself can codify the accepted practices so that you don't have to list them all individually in the coding standards; just specify the tool's configuration.

Note: The "coding standards" idea is not unique to programming. "Coding standards" are used in many fields, sometimes within an organization, more often across an entire industry or profession. Some examples:

In each case (and many others) a competent practitioner could easily understand "code" that doesn't meet the expected standard. Why do so many industries persist in writing detailed requirements for documents that don't even need to be parsed by a compiler? Because style matters. Presenting information in a standard style lets the reader focus entirely on content, makes reading faster and aids understanding, and reduces errors.

+1 for the "... immediate relocation ..." as in my experience such behavior is consistent with sociopath and/or narcissistic tendencies, incompatible with software development teams.
–
mattnzSep 14 '11 at 2:09

Amen! Coding standards need to be justified in terms of real benefits and consistency isn't a real benefit, but a luxury.
–
JohnFxSep 13 '11 at 19:10

12

But style is rarely about style. It is about avoiding common errors.
–
Loki AstariSep 13 '11 at 20:15

5

But it does help avoid '=' instead of '==' (don't use assignment inside the condition). It helps avoid if (t) { x;y;} rather than if (t) x;y; (always use '{}' after if). Prefer const correct code (it is very hard to add const correctness into code after it has been written. Use std::cout/std::cin not fprintf/scanf the former are much more likely to cause errors. Use vector rather than arrays (to help prevent overflow).
–
Loki AstariSep 13 '11 at 21:05

5

Getting it to work is obviously paramount. But just because it works doesn't mean it's done. It also needs to be tested. And then reviewed. That all might take a few days. Then, for years afterward, it has to be read and understood and maintained. Useful code (why write any other kind?) will be read many more times than it's written, so making it easy to read and understand improves productivity far into the future. Using a consistent style across the organization is one way to help in that respect.
–
CalebSep 13 '11 at 22:21

1

What about enforcing the use of automatic formatting tools? Eclipse and XCode make it very easy to keep code formatted - but one of the engineers I work with gets extremely upset if someone autoformats "his" (i.e. the company's) code to keep it consistent with the rest of the codebase. Formatting is only a small part of style but it's also an important one, especially for issues like if/else nesting and overall code flow (not to mention readability).
–
fluffySep 13 '11 at 22:26

Generally, there is the coding standard which is the guidelines which can be ignored, interpreted creatively or modified for given needs. And there's the section on "smells" and it's to be obeyed rigorously.

Create consistency with a good upfront design. What you describe in the question is nothing less than micro-management. I do a lot of web development. So I favor RESTful and CRUD development exposed as services. This ensures simple, well defined entities that can be used in a variety of ways.

This design also allows me to delegate implementation details to other developers. This way they are filling in the blanks rather than creating a whole system design.

A lack of an overall design creates system inconsistencies. Critique of basic iterations and looping constructs does little to improve system design. These kinds of problems are better solved with a hands off approach, StyleCop.

Can you draw a relatively simple diagram of your overall system design? A design describing the elements/entities involved in a to a new team developer. If you cannot, or it is highly involved then the design is lacking.

Your first two examples are not just a matter of personal taste to me.

if (condition)
// Do this one-line code
else
// Do this one-line code

(without brackets) = more bug-prone, if more code is added later on:

if (condition)
// Do this one-line code
else
// Do this one-line code
// ...and this line as well... oops! this will actually execute either way

And this is less convenient to debug:

new HelperClass().DoSomething(GetSomeData()); // etc.

You cannot simply set a breakpoint where you need it. If this is a one-off - fair enough, but we discuss it as a matter of style, and once you've got stuff like this all over the place, debugging gets more unpleasant than it has to be.

As for your third example (for vs foreach), I see it as a matter of taste though.

Neither. I would avoid harsh coding rules to avoid being tedious, nit-picky, micro managerial and worst of all wasting time. Your sense of autonomy is your own issue. If I want you to feel better about yourself, I'll buy you a round of your favorite beverage. Other than that, get something done.

Use of conventions, variable names, class names etc. is good practice. But coding styles like the examples you provide are rather trivial and have no effect on either the readability or efficiency of the code. On the other hand, the overhead from enforcing a given style combined with the developers effort to following it will cause problems.

It's a mixture of both. Just because it's a standard doesn't make it readable and maintainable. If there is no instilled standard yet, or it there are faulty and unreadable aspects of it, revision is appropriate.

In the final analysis, it's the programmer that drives the programming. Style issues exist, but they are secondary to getting the program out.

It IS helpful to give programmers SOME style guidance. This can/should be done before the programmers are put to work, especially if they are relative beginners to the environment, or to programming itself. Given guidance, some programmers will be very style conscious, others less so. The guidance given at the beginning of the project will help the first group of programmers, thereby making the overall task easier. It might do little for the second group, which will (hopefully) make up in creativity, what they lack in conformity.

I think it comes down to the size of the project, and how many people are working on it. A skilled programmer can look at both differnt format styles and know what was going on in both of them but there needs to be a consictancy so the eye can catch it easily. If your going to do your single line ifstatments with out the curle braces then that project should not use them Who ever is leading that project should have that choice. I like things to look clear cut and also very compact as i can get them. If your going to make an a single line if statmeents they better looks like this

if() {}
else() {}

Or even:

if() {} else () {}

But a single line if should not use the spacing of a mulitiline if. It is just how I do things. I dont mind the way the object is called and that depends on how many times its called. if its getting called a few times then i rather start the object and depends if it has constuctors and what not also. Because if you have a constructor and you call:

Object.method();
Object.method2();

Then you ended up call the the object constuctor method twice when it could have been avoided by instancying the object fully.

When it comes to foreach and for loops Its also about the lanauge some lanauges give you better control when looking at the array in a foreach loop so you have the key and the value in temp arrays. And I know some lanagues have some sort of optimization because they can look at the loop and know exactly how many times its going to get called.

While your first example is not great (the argument that it's more bug-prone under modification carries some weight), in general I've actually grown to prefer that developers use slightly different coding styles.

After working with other team members' code, sometimes for as little as a few months, it essentially starts to work line an in-line svn blame. After having been at my company for 10+ years, I can probably tell you with 80%+ accuracy who wrote any given class anywhere in our 500k lines of code, just by looking at it.

While there is a tiny bit of "ramp time" when you start looking at code that uses a style you don't agree with, what you're really doing in that time is saying "oh, this looks like John Doe's code (because he uses style X but not style Y, etc.)". And that brings with it a whole heap of context. To a first approximation, you know what to expect from John's code -- what other parts of the codebase he understands well and what parts he doesn't, whether he's an SQL guru or a GUI novice, etc. etc.

Running everyone's code through a formatter essentially strips out this information, hiding it behind an svn blame, which you may not bother to run.

If you're a small group of superheroes, then any type of style is fine. If everyone has their own style, and it's both good and internally consistent, then that's all the process you need. The Superheroes will say, "Jane has brackets, so this is what she means" or "Jack uses camelCase for variables".

Universal standards tend to be best for making everyone a B+ player. Your superheroes will get pulled down by this. But if you want one A player and a half dozen B players and a half dozen C players to average up to the B+, then you want consistent standards. In this instance, you want everyone doing things the same so that the one A player can walk through everyone's code as quickly as possible.

Many of you way, "But wait, why not do away with the B and C players?"

The reality is there aren't many Superheroes. While it may pay to find and nurture them at Google, putting in a new billing system for Ma Bell may be more cost effective with the latter team. (And if you really have Superheroes, 4 or 5 of them will be twice as expensive as a dozen juniors)