97

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.

gnat
  • 20,543
  • 29
  • 115
  • 306

17 Answers17

122

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.

ZeroOne
  • 956
40

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

mattnz
  • 21,490
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.

NPKR
  • 347
  • 2
  • 4
19

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.

jwenting
  • 10,099
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.
vaughandroid
  • 7,609
10

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.

rajah9
  • 231
8

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.

Sam
  • 121
  • 2
7

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.

JeffO
  • 36,956
6

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!

keredson
  • 121
4

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?

Gur
  • 101
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.

Jonesi
  • 49
  • 2
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.

Jeff Putz
  • 154
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.

swpalmer
  • 101
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".

ahill
  • 205
1

Lets look at it from the point of view of a developer. Lets suppose the developer is me.

So, I join your company and got enforced to follow a certain coding style. Nothing technical. Just a bunch of rules for aesthetics and "readability". Yes that word needs to be in quotes because its not a universally agreed on format for readability. It can be easily readable for some and hard to be read for others.

Before one attack on my coding style, that lets suppose go against the enforced company coding style, one should look at the reason why I adopted that coding style. Before one destroy a thing one has to be sure that it dont serve a purpose greater than what can be achieved by its destruction.

The reason I adopted a coding style is to be consistent ACROSS JOBS. I have a career and that career has multiple jobs in it. I have no plan to spend rest of my life in the job I just joined. I need to grow, both financially and technically, and the most effective and often the only way to do that is to switch jobs. Also, its healthy for an economy for companies to sometimes fail.

So, what you are asking me is to learn and adopt a new coding style every time I switch jobs. Whats good for you company is also good for other companies or you are just freeloading over hardwork of others.

The thing is, my coding style is very dear to me. Its what I have developed over years and it serves me well. Its a big reason for my current productivity. Its dear to me also because I spend 8 hours a day with it. Its not something I can depart with without not only a valid reason but an overwhelmingly benefical reason for me.

I can adapt, once may be but I cannot repeatedly adapt changes to something this basic. Its a huge ask for me without any real benefits for me.

Lets be real, how often do I need to code review other people's code. Not often. Negligible percentage compared to time I spend with my own code.

What about modifying code other people have written? After all we developers have to work together on projects. The answer to that is, I have to seldom make changes to other people's codes, most of the time I have to just add code. The difference in percentages of when I do what is a lot, a factor of 10 may be.

Most of the time I just have to look at other people's code and get a general idea and then add code to it. May be 5 percent of time, may be 10 percent of time I have to actually edit functions and logics written by other people, may be stretch that to 15 percent for you. If the functions are well written, if the code is reasonably modularized then there is little need to modify it. Look at the Open-Close principle, polymorphism and composition. They are there to reduce need to modify existing code.

All in all its a bad decision for me to part with something thats so near and dependable for me. I am not even making a trade off here. Its not that I earn better in your organization at cost of taking a new headache. I will just leave and find job elsewhere which have roughly the same pay.

Also, one's coding style is very closely related to one's formatting style. One enforces other and they grow together. Asking me to change my formatting style is asking me to change the way I think. I doubt that I am even able to do that. To do that I have to think and you are asking me to change that very thing, talk about a catch-22.

Its not just those things either. Its also asking me to throw away various lessons I learned in my decades of experience. The way of thinking I developed is different from the way of thinking you developed because we have different life paths, we work on different projects over years and organizations we made our career in.

We learned different lessons because of those different experiences. Those different lessons are beneficial for not only the individual us but also the collective us. We can learn from each other's learned lessons. If we all have to think the same way then there is no advantage in code reviews. If one of us make a mistake none of us will be able to catch it. You will get a huge productivity boost at start, may be, if developers stay with your organization, but its almost a guarantee that your entire organization will fail, fail hard, and fail soon. Its because you have removed the fall-backs, the watching of each others' backs (through code reviews) and having multiple point of views and ways to solve problems.

Atif
  • 144
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.

Kristian H
  • 1,281
-1

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.

Josh
  • 105
  • 3