96

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.

14
  • 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
    – gnat
    Mar 5, 2013 at 8:50
  • 10
    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? Mar 5, 2013 at 14:54
  • 30
    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. Mar 5, 2013 at 15:20
  • 5
    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.
    – Benedict
    Mar 6, 2013 at 11:56
  • 4
    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. Jun 8, 2013 at 10:45

17 Answers 17

118

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.

5
  • 23
    +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.
    – Marco
    Mar 5, 2013 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. Mar 6, 2013 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.
    – Giorgio
    Jun 8, 2013 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. Jun 9, 2013 at 10:44
  • Stricter warnings and errors are a good thing. Dec 18, 2017 at 13:31
39

Every professional software developer will prefer to adopt a (good) standard rather than get into evangelical wars over style, for the very reasons you have outlined.

Many software developers wage evangelical wars......

Depending on your position within the team and the team dynamics, you may decide that winning the war is not possible. In this case, it may be best not to start...

9
  • Tx, I know exactly what you mean Mar 5, 2013 at 8:58
  • 17
    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.
    – ZeroOne
    Mar 5, 2013 at 15:29
  • 10
    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). Mar 5, 2013 at 15:43
  • 3
    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. Mar 5, 2013 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. Mar 5, 2013 at 19:17
31

Yes, that is good to have one code format styles for all developers.

Design the code style formats and import that to all developers eclipse.

This will help when we are merging code to 'Version control' system.

7
  • 6
    +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.
    – pgras
    Mar 5, 2013 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)
    – BiAiB
    Mar 5, 2013 at 17:21
  • 1
    "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.": I am not sure I understand the use case: every commit will change certain lines that will show up as a diff. Or do you mean there are developers that reformat the whole file before committing their changes?
    – Giorgio
    Mar 5, 2013 at 21:24
  • 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… Mar 5, 2013 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).
    – Giorgio
    Mar 5, 2013 at 21:48
18

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?

  1. 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 :)
  2. 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.
  3. 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.).
  4. 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.
  5. 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.

7
  • 1
    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). Mar 5, 2013 at 13:46
  • 1
    +1 for KISS. @Stijn Why reformat old code? Just hit it when you need to modify it. Mar 5, 2013 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. Mar 5, 2013 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. Mar 5, 2013 at 16:25
  • 2
    you forgot another reason Dan: large scale formatting changes can easily introduce new bugs in unexpected places.
    – jwenting
    Mar 6, 2013 at 6:55
12

Yes, consistency is a good idea, for reasons others have mentioned.

I just wanted to add a couple of points which haven't been used elsewhere:

  • Oracle has published a set of conventions for Java, which are the de facto standard.
    • Using these should help you avoid arguments about which style to follow.
    • A lot of public libraries and open source projects tend to use these conventions, so when you need to look at those the formatting should be familiar.
    • The Eclipse formatter has built-in rules to match these conventions, which should also help.
  • You might want to consider building a hook into your source control setup so that code gets auto-formatted before it gets into the main branch.
    • You can avoid battles with particularly stubborn programmers who refuse to follow the standard. They can even use their own formatting while they work, which will get standardized later!
    • If you end up using custom formatting settings (e.g. a lot of people ignore the "max 80 chars per line" convention) you only have to make changes in one place.
9

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.

2
  • 5
    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…) Mar 5, 2013 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.
    – rajah9
    Mar 5, 2013 at 22:30
6

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.

Personal preferences are just that and rarely improve production: https://stackoverflow.com/questions/249432/whats-the-reasoning-behind-the-different-brace-forms

If it does, get over it and get something done.

6

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

  1. 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.
  2. 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.
  3. Enforcement of code syntax is best done with code reviews:
    1. If formatting is important, than it draws your organization to do code reviews. This is of huge benefit.
    2. 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.

2
  • 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. Mar 5, 2013 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.
    – Sam
    Mar 5, 2013 at 15:24
4

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!

3

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?

2

Good developers are creative people, give them some artistic licence. "Keep it simple" should be the programmers mantra. I have two rules:

Rule 1: Give variables / cursors / objects / procedures / whatever SENSIBLE NAMES. Unambiguous names that bring meaning and understanding to your code.

Rule 2: Use indentation to show the structure of your code.

That's it.

7
  • 1
    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?
    – user40980
    Mar 5, 2013 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.
    – Jonesi
    Mar 5, 2013 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?
    – user40980
    Mar 5, 2013 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. Mar 5, 2013 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.
    – Jonesi
    Mar 6, 2013 at 0:10
2

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.

2

One format to rule them all... is it really optimal?

It's like driving someone else's car...

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.

Have formatting rules, but allow some freedom to apply common sense.

1
  • 2
    I absolutely agree! Autoformatters are dumb. Sep 3, 2015 at 7:21
0

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.

-1

Style guides also enable easier programmatic parsing of code for various analytical purposes.

Google has published a paper about this called "Searching for Build Debt: Experiences Managing Technical Debt at Google".

-1

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.

-2

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

  1. If I am writing code in one format and it is automatically reformatted, what incentive is there to actually learn that format?
  2. 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
  3. 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.
  4. 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.

1
  • +1: Good points, though I'm not sure they outweigh the reasons in favor of automated reformatting. Why the downvote(s)?
    – user25946
    Mar 6, 2013 at 0:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.