We are considering to impose a single standard code format in our project (auto format with save actions in Eclipse). The reason is that currently there is a big difference in the code formats used by several (>10) developers which makes it harder for one developer to work on the code of another developer. The same Java file sometimes uses 3 different formats.

So I believe the advantage is clear (readability => productivity) but would it be a good idea to impose this? And if not, why?

UPDATE
We all use Eclipse and everyone is aware of the plan. There already is a code format used by most but it is not enforced since some prefer to stick to their own code format. Because of the above reasons some would prefer to enforce it.

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

2

do all of your developers use Eclipse? did you talk to them about this plan? Without knowing this, your question is difficult to answer, one would have to guess too much
– gnatMar 5 '13 at 8:50

9

Does it actually make it harder for one developer to work on the code of another, or are developers just being allergic to reading slightly different code?
– Joris TimmermansMar 5 '13 at 14:54

27

When you use a Scource Code Control System (like svn), make sure that changes in code formatting are comitted separately from semantic changes - otherwise it will be difficult to find those semantic changes.
– Martin SchröderMar 5 '13 at 15:20

4

I disagree with Martin here, well sort of. My rule of thumb is if you make a logical/semantic change, then you are allowed to change the format of the lines you changed, otherwise you aren't allowed to change the format of lines just because you fancy it. Don't clog your version control log with petty reformatting changes.
– BenedictMar 6 '13 at 11:56

3

On the other hand: if everyone uses the same format, only the first commit to reformat everything will be clogged with it. Everything else will just touch the local changes made, which is acceptable in my opinion.
– Jeroen VannevelJun 8 '13 at 10:45

17 Answers
17

I currently work at a place where a standard code format is enforced and the code is automatically formatted when saving the file, just like you are about to do. As a new member of the company I found that the common formatting rules gave me a warm and fuzzy feeling that "these guys know what they are doing", so I couldn't be happier. ;) As a related side note, with the common formatting rules we also enforce certain, rather strict compiler warning settings in Eclipse, with most of them set to Error, many set to Warning, and almost none set to Ignore.

I'd say there are two main reasons to enforce a single code format in a project. First has to do with version control: with everybody formatting the code identically, all changes in the files are guaranteed to be meaningful. No more just adding or removing a space here or there, let alone reformatting an entire file as a "side effect" of actually changing just a line or two.

The second reason is that it kind of takes the programmers' egos out of the equation. With everybody formatting their code the same way, you can no longer as easily tell who has written what. The code becomes more anonymous and common property, so nobody needs to feel uneasy about changing "somebody else's" code.

Those being the main reasons, there are others as well. I find it comforting that I don't have to bother myself with thinking about the code formatting, as Eclipse will do it for me automatically when I save. It's care-free, like writing documents with LaTeX: it's formatted afterwards and you don't have to worry about it while writing. I have also worked in projects where everybody has had their own styles. Then you have to think about stupid and meaningless issues such as if it's OK to modify somebody else's code in your own style, or if you should try to imitate their style instead.

The only argument against common code formatting settings that I can think of for your case is that it's apparently an already ongoing project, so it will cause lots of unnecessary changes in all the files, messing up the actual file histories. The best case scenario is if you can start enforcing the settings right from the beginning of a project.

+100 on taking programmers' egos (and ownership) out of the equation. Programmers' laying "claim" to parts of the code does not contribute to productivity because it impedes knowledge sharing and means that there's a signal given that not all programmers could work on the same piece of code.
– MarcoMar 5 '13 at 21:48

It was difficult to decide which answer to accept but I found this one to be the best argumented and also best addressing the actual question.
– Stijn GeukensMar 6 '13 at 19:25

"means that there's a signal given that not all programmers could work on the same piece of code": Well, but this is actually something you may want to have: as long as you are not familiar enough with a piece of code, you should not work on it / modify it. Too much shared code ownership can lead to everyone working on the whole code base and no one really mastering any part of it.
– GiorgioJun 8 '13 at 3:09

I'd have a lot more time for this kind of thing if the code were automatically formatted to my style on load. When Roslyn lands for C#, I hope to see all loading, saving, versioning and so on work on the AST instead of the text.
– Mark RendleJun 9 '13 at 10:44

Stricter warnings and errors are a good thing.
– Christophe RoussyDec 18 '17 at 13:31

It's not professional to wage wars about code formatting. A professional software developer will get things done just as well no matter if their code reads "if( foo )" or "if (foo)". If you really need to sell this kind of change to someone, you should appeal to the fact that they are professionals. They can't talk back or they'll appear anal-retentive. If someone does anyway, well, I hope for your sake they'll find a new job soon.
– ZeroOneMar 5 '13 at 15:29

7

A professional developer would also write readable code, and be able to read other professional developers' code quite easily, obviating the need for an extensive standard in the first place. I would worry that here "the standard" is a bad fix for the wrong problem (you don't fix sloppy devs with a coding standard).
– Joris TimmermansMar 5 '13 at 15:43

2

The best way to try and sidestep most of these holy wars is to accept language defaults where ever possible. Yes that means your coding style will vary across languages (ex C# code will have {'s on separate lines java will have them on the prior line, and what's PascalCased or camelCased will vary); but each individual languages source will look 'normal' when you bring new developers on to the project.
– Dan NeelyMar 5 '13 at 16:30

1

@ruakh Look at MSDN C# code samples, look at how Visual Studio reformats C# by default: { is on it's own line. Repeat the exercise for Java in Oracle's documentation and Eclipse's defaults when reformatting code: { is on the line above.
– Dan NeelyMar 5 '13 at 19:17

+1 for mentioning merging and diff tools. It's a real pain to try to spot differences between two versions of a code base when the formatting is not consistent between developers.
– pgrasMar 5 '13 at 16:48

1

+1, I highly second the version control system argument. (but it's mostly because of indentation rules. things such as naming conventions don't have as much impact)
– BiAiBMar 5 '13 at 17:21

Naming conventions help when you need to figure out what a method you know exists in a class is called.
– Dan NeelyMar 5 '13 at 19:18

1

@Giorgio There are indeed developers who do that. While mixing with other changes too (e.g., critical bug fixes). Some things are sent to try us…
– Donal FellowsMar 5 '13 at 21:26

1

@Donal Fellows: You are right. I follow the principle that every character you type in a source file is (1) a potential error (2) introduces a change that makes the code difficult to recognize afterwards. So in my opinion each change should be as small as possible. But, yes, there are developers who change the code without thinking too much. I wonder if an automatic reformatting of the code can solve the problem. I would rather be in favour of code ownership (see e.g. point 7 at paulgraham.com/head.html).
– GiorgioMar 5 '13 at 21:48

What are you trying to gain, how anal retentive are you going to be in enforcing it (and in the level of detail your "rules" will be set out), are you going to try to enforce it on code written in different languages, are you going to try to enforce it retroactively on existing code?

a common look and feel to code can indeed help make code more readable, but also can make things worse if it's the wrong look and feel. _hUngarian_lpfstr notation being a prime example :)

I've seen "code standards" enforcing the number of spaces of whitespace between in comment blocks, the alphabetical ordering of method names, and other nonsense. Don't do that.

Different languages have different standards people are used to who're experienced in their use. Some even mandate these standards (think Python, Cobol, Visual Studio automatically imposes C++ style bracing conventions while Java uses C style by convention, etc. etc.).

never change existing code for the sake of changing it, you're only introducing new problems that way. And that means code sections as well as entire source files. So don't go around reformatting existing code when someone changes a single line in a 1000 line file.

experienced programmers can be much more productive if they don't have to think half the time whether what they're writing will "look right" to the automatic approval system, or the reviewer. They're also going to be in the habit of writing clean code simply because that's what works, even if there are small differences between their natural styles.

So while there are good reasons to impose a specific style and standard, there's as good reasons to not do so (too) strictly.

1-2-3: It's Java and the code format is the one from Sun; it's just formatting so not ordering methods or variable names; 4-5: well, the idea would be to automatically format on save (Eclipse save actions) so no extra work (you don't even need to think about the format while coding) but of course also existing files would be reformatted (the first time).
– Stijn GeukensMar 5 '13 at 13:46

1

+1 for KISS. @Stijn Why reformat old code? Just hit it when you need to modify it.
– Erik ReppenMar 5 '13 at 14:38

3

Actually, we are planning some major refactorings and would reformat all code at that time since merging will be almost impossible anyway because of the refactoring. If we only reformat on change then we will still face merge issues because of changed format a year from now.
– Stijn GeukensMar 5 '13 at 14:57

4

I generally agree with @StijnGeukens ; not just for merge reasons, but because any large scale formatting cleanup will make following change history in a blame tool across it difficult. If all your noise changes are at a single location you can just always set blame to begin before that point initially and then do a second round stopping before it if you need to look at older history.
– Dan NeelyMar 5 '13 at 16:25

2

you forgot another reason Dan: large scale formatting changes can easily introduce new bugs in unexpected places.
– jwentingMar 6 '13 at 6:55

I was on a team that used the Checkstyle plugin. Rather than use the out-of-the-box features, we formed a small committee of interested developers. We debated over what seemed missing, what seemed excessive, and hammered things out. We all learned something in the process, and strengthened those developer muscles.

(Examples of our decisions: 72 characters wide is too small, but 120 was better; it's better to use _ALLCAPS for static finals; enforcing single-exit from a function is a good idea.)

When we had code reviews, one of the first questions was: "Have you run it through Checkstyle?" Complying with the coding standards was largely automated, and it drew the attention away from the reviewer being picky. It was wonderfully easy to have Checkstyle highlight a method signature, right-click, and change a variable to final. It could also fix the indentations and braces so that everyone's code had a similar look and feel. Missing a Javadoc for a public function? Checkstyle will flag the function.

(Removing code smell is more important than consistent formatting. This is a benefit of automated tools.)

I would place automated tools like Checkstyle less as imposing the same format and more on encouraging a similar look and feel. And when you're herding cats, an automated tool can help sharpen skills and reduce code smell without bruising fragile egos.

Single exit point? There are certain style principles that I truly don't agree with. (If multiple exits are a problem, the function/method is too long in the first place…)
– Donal FellowsMar 5 '13 at 22:21

@DonalFellows, Checkstyle gave us a reference point from which we could shift towards the committee's preferences. There were many exclamationss of the nature, "I don't see why they put this standard in!" While the OP was asking about consistent formatting, I think the automated tool gives a lot more without additional pain.
– rajah9Mar 5 '13 at 22:30

If you're going to stick to the same IDE and incorporate some formating tools, it's a good idea because you're not requiring too much effort. Keep the rules simple with a focus on readability and not anal retentiveness. That should be the measuring stick.

Although a consistently formated ball of mud is better than just a ball of mud, your time would be better spent cleaing it up instead of getting too picky about where the brackets go. Don't turn into the pin-headed manager who feels like they're doing their job by counting indent spaces during a code review along with making sure the new cover sheets are on the TPS Reports.

I strongly recommend that humans enforce code formatting, and that minor infractions are graciously overlooked or touched-up. Reasons for this are, briefly,

The machine gets it wrong at the worst possible time, and usually when you are using a new language feature. How will it handle closures in Java, etc? Jalopy has trouble with enums with member functions.

I think it's a very reasonable burden to put on the programmer to please produce code for the company that looks like company code. I've found it helpful to mention that this is how code is formatted "here," not how all code should be formatted everywhere. Their previous company may have chosen a different path, and that's OK. Not unlike vernacular language, there are idioms specific to your code culture that you want to bring out.

Enforcement of code syntax is best done with code reviews:

If formatting is important, than it draws your organization to do code reviews. This is of huge benefit.

If a formatting rule is broken, a human can look at it and judge better than a machine if the intent is conveyed more cleanly. This is very rare, but happens occasionally.

Regarding "readability => productivity", code structure (such as single-responsibility classes and functions) will buy you far more faster than code formatting. Code formatting can be a help, but different minds parse statements differently -- not everyone will be "more productive." I would like to double-down on code structure over formatting because that is something that will also pull you into doing code reviews and get the team into thinking about how the program works, not how a single loop looks.

I'm not a big fan of Domain Driven Design, but it is one recent model that has a VERY well defined idea as to how code should be structured and code formatting conventions flow naturally out of a Domain Driven Design structured program. Again... I don't like DDD, but it's a great example because it's so well defined.

I suppose the theme of this answer is, Do code reviews and let formatting flow from the culture and out of the review process.

Tx, not a bad point of view this. But then again, it's extra work if during each review the reviewer must check the format as well.
– Stijn GeukensMar 5 '13 at 15:02

3

It's an extra click to call-out a line in something like Fisheye as, "inconsistent indent" or "open-brace on line by itself," so, yes, it's more than zero effort. However, if this extends code reviews by more than literally 1 minute there is a gross problem. After a week of the team reviewing its own code, they should all be very fast at noticing "wrong" code and touching it up.
– SamMar 5 '13 at 15:24

Generally, assuming you hire reasonable developers, it is a bad idea to impose a universal code format. It is however a good idea to adopt code guidelines.

I've never seen a set of code formatting rules that optimizes readability in all cases. Likewise there are no 100% applicable grammar rules in English: our brains just aren't wired that way. So use guidelines, but give developers the freedom to override them as they see fit.

That being said, a harder rule of "follow the code convention that already exists in the file/project" is a good one.

But keep in mind that the formatting contributes much less to the readability than simply how logically organized the code is. I've seen plenty of unreadable spaghetti code w/ perfect formatting!

I don't think there's a simple answer to this. It's not a yes or no question. While I believe that style and naming conventions are important to an extent, it's also pretty easy to waste too much time thinking about it. It's best to answer by example.

On one particular project I was on, there were no conventions at all. Every developer did things in their own way. Because of the relative inexperience of this team, going from one class to the next was really jarring. The style was less of an issue than the naming conventions problem. One developer would reference UI elements with awful Hungarian notation (a silly practice in the age of modern IDE's), one would name private members one way, another would name them differently. You just never knew what you were looking at.

At the opposite extreme, one team used StyleCop (this was a .Net project) as part of their build process. What's worse, is that they also used most of the default rules. So you would do something totally normal in terms of line spacing or curly bracket placement, and the build would puke because of it. So much time was wasted just adding spaces and lines to stuff, and everyone, including the dudes who insisted using StyleCop, ended up doing it almost every commit. It was an enormous waste of time and money.

So the point I'm making here is that being inflexible isn't the answer, but being in the Wild West isn't either. The real answer is to find the place that makes the most sense, which in my opinion is to not have automated tools checking stuff, but not throwing convention to the wind, either.

My main argument against common coding style is that an experienced programmer is used to read his own style. You can train the hand to write a specific style but it is nearly impossible to train the eye to understand a style that you hate. A programmer writes some piece of code once and then reads it again and again during development and debugging. If every time he reads his own code he struggles to understand it since he was forced to write it in a BAD style he will be very unhappy and less productive. This is from my on experience.

I am not too familiar with Eclipse but auto format on save sounds like an horrific idea.
A developer must have complete control over his code regardless of whether coding style is imposed or not. 'save' operation must not change a single character without explicit consent from the user.

If your company sells source code then coding style is more important but if you sell compiled code then it is much less relevant.

Hoping that coding style will make the original coder less distinguishable and prevent ego wars is bullshit in the best case and plain stupid in the worst case. Great programmers will always produce elegant code regardless of the style.

I am also strongly pro giving every developer ownership of specific code units and against letting everyone touch every piece of code freely. Developing whole units in the code and being responsible for them allow the developer to grow pride in his work and prevent him from developing crappy code knowing that bugs will return to hunt him.

Finally, anyone who is pro coding style always assume that his own coding style will be selected and everyone else will follow. Imagine that the coding style you least like from all of your co-developers being selected as standard. Are you still in favor of imposing coding style?

Sure you can hop in and drive any car, but you will be safer, more comfortable, and less likely to crash if you take the time to adjust the seat, steering wheel and mirrors to YOUR preference.

With code, the formatting does affect your comfort in reading and understanding the code. If it is too far from what you are used to it will require more mental effort. Is it necessary to inflict this on the developers?

+1 to all the benefits mentioned so far, but...

Automatic enforcement comes with costs that need to be considered:

-1 to the fact that code formatters don't understand aesthetics of code formatting.
How many times have you had a code formatter destroy a comment block that was nicely aligned in a tabular form?
How many times did you purposely align a complex expression a certain way to increase readability, only to have automatic formatting mangle it into something that "follows the rules", but is far less readable?

Sometimes there are workarounds to these things, but developers have more important things to put their mind to than how to keep the automatic formatter from mangling the code.

Could you explain why this is the case? How does letting each developer have some artistic license (that differ between developers on the same project) make for a better idea than having all of them have the same format? Are there any problems yours solves that the alternative doesn't? And vice versa?
– user40980Mar 5 '13 at 21:27

I guess the point I am trying (and failing) to make is that using sensible names and indenting your code well is far more important with regard to readability / maintainability than other rules you may care to invent. I'm not saying everyone on the team should have their own style, just that if they do then so what.
– JonesiMar 5 '13 at 21:37

Consider if I have a code formater in eclipse set up one way and I always reformat my code... and you have one set up slightly differently... and we keep modifying the same code. Does this 'artistic license' cause any problems in the diffs?
– user40980Mar 5 '13 at 21:57

While I understand the point you are making I think that a problem with your point of view is when you have widely differing styles (note, not wrong just different). This can cause real problems and delays when merging these different styles.
– Daniel HollinrakeMar 5 '13 at 22:08

1

Yes, I get your point Daniel. I should add a third rule: When modifying existing code, adapt to match the style of the code you are editing. This is what I would naturally do if I was fixing an old program.
– JonesiMar 6 '13 at 0:10

For me, the main advantage of a common format automatically applied is that it helps our change tracking & code reviews. git (and most other source control tools) can show diffs of previous versions of the files. By enforcing a common style, it minimizing programmer preference diffs.

It's languages not codes. We humans have more than 6000 languages so we translate them. So if you want your "codes" to communicate you'll have to make your adjustments. You see we users have to change our data formats so we won't loose our data.

I would say it isn't. A common code structure/format among a team is most definitely a good thing, but automatically enforcing it is not. This should be done by humans, not by the computer.

My biggest issues with the concept are

If I am writing code in one format and it is automatically reformatted, what incentive is there to actually learn that format?

Following that previous point, if you do not learn the format, the entire point of autoformatting (to make code more easily read and modified) is completely lost. You still have to take time to figure out the formatting as you are reading the code because you have not learned that format

I think it would be a jarring experience as a dev to write a class one day, close it, and return the next day to see it is completely different. That means that not only do others have to learn your code, you have to learn your code.

It could also encourage lazy coding. Instead of pushing the dev to learn the format, they can write in any format under the sun and it will automatically look the way everyone else wants it to. This goes back to #2 where you don't learn the style and still cannot read it correctly.

Now, I might be inclined to say that running an auto-format on a project that is all wrapped up would be a good idea. This would start every dev off on the same foot for the project when you go to fix/add features later on. During active development, however, I think it is a very poor choice.

Basically: Put the responsibility on the employee to learn the style of the company, don't force their code to be something that it isn't.

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).