views:

212

answers:

13

Does it make a difference if you choose a non-standard indent style?

This is the style I see most often:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test {
  static public void main(String args[]) throws Exception {
    FileInputStream fin = new FileInputStream("infile.txt");
    FileOutputStream fout = new FileOutputStream("outfile.txt");

    FileChannel inc = fin.getChannel();
    FileChannel outc = fout.getChannel();

    ByteBuffer bb = ByteBuffer.allocateDirect(1024);

    while (true) {
      int ret = inc.read(bb);
      if (ret == -1)
        break;
      bb.flip();
      outc.write(bb);
      bb.clear();
    }
  }
}

But I prefer this style where everything starts on the next line:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test
{
    static public void main(String args[]) throws Exception
    {
        FileInputStream fin = new FileInputStream("infile.txt");
        FileOutputStream fout = new FileOutputStream("outfile.txt");

        FileChannel inc = fin.getChannel();
        FileChannel outc = fout.getChannel();

        ByteBuffer bb = ByteBuffer.allocateDirect(1024);

        while (true)
        {
            int ret = inc.read(bb);
            if (ret == -1)
                break;
            bb.flip();
            outc.write(bb);
            bb.clear();
        }
    }
}

I find this easier to read but will I encounter problems working with others if I use this style?

+2  A: 

It doesn't matter. Most companies use a code formatter anyways.

I also prefer the second style.

vash47
"Most companies use a code formatter anyways.": Does that mean the code is formatted in a standardized way before it is checked in to the version control system? In other words, it doesn't matter what style individual coders use on a team since they will all look the same in the code repository?
glanden
What do you mean, "Most companies use a code formatter anyways"? Doesn't that lead to the problem duffymo mentioned with spurious changes in version control?
Kirk Woll
@Kirk Woll: I think he's saying that an automated process formats the code before the checkin process completes. I didn't know such software was available but it seems like a great idea. I'd love to know an example of such a system so I could try it out myself.
glanden
@glanden, yes, but I've never heard of such a thing. And to suggest that "most companies" do it seems like hyperbole.
Kirk Woll
@Kirk Woll: I agree. "Most companies" seems like an exaggeration. I've worked in a lot of companies and never heard of anyone using a code formatter so I'm very curious to hear more about this as it sounds very useful to companies and liberating for coders.
glanden
@glanden: A common one for Java is JaCoBe ( http://www.tiobe.com/index.php/content/products/jacobe/Jacobe.html ). There are others for other languages, too, often named using variations of "tidy" or "beautifier". But see Kirk's comment reply to Tony Ennis below for one of the caveats of misusing automatic source formatters.
Simon
@Simon: Thanks for the link! Good to know.
glanden
I've never worked at a company that used a formatter to format code automatically. It's always been at the programmer level if/when it is remembered.
Tony Ennis
+4  A: 

It doesn't matter which style you use, but make sure it's consistent with the rest of your team.

Usually this involves endless discussions but I guess that the 2 ones listed here are the more common ones.

Pablo Fernandez
Wish I could upvote you ten times!
slashmais
And use automatic formatting. This will ensure that the source repository does not consider reformatting to be a change at a later time.
Thorbjørn Ravn Andersen
+1  A: 

You will not have problems with others if they all use the same brace placement and indentation standard as you do.

You will have problems if you're a lone wolf.

The biggest issue will be with your version control system. You don't want people to "oil can" between styles and have lots of differences showing up because of style changes rather than substantive code modifications.

When in Rome, do as the Romans do. Come to a consensus in your team and stick with it.

PS - I'm with you: I prefer to have braces on the next line. The Sun convention is the first one. It's better for book authors, because there's less white space.

duffymo
A: 

As ever when it comes to code formatting, it is risky if you work with someone who prefer the other one.

Vivien Barousse
The other one should hold to the same principles.
slashmais
+4  A: 

Stick with conventions. You should be looking at code outside of your immediate project, programmers move, companies are acquired, tools will tend to be configured for the standard, etc.

Tom Hawtin - tackline
The effort to make the switch from one coding style to the other is literally of hours (personal experience here).
Pablo Fernandez
I';ve been lucky enough that everywhere I've worked has used the same general style as I always have. However, whenever I have to read code written in the other style it causes additional mental load which I could really do without.
Tom Hawtin - tackline
@Pablo - not if you use IntelliJ. It can set project-wide coding standards in seconds.
duffymo
A: 

I stopped worrying about code formatting long ago. What a waste of oxygen, to argue about placement of curly braces. When I have to modify code, I reformat the file with the IDE's code formatter, using the defaults. Then I do my work and commit it. When someone else changes the file, they can format it to their liking. I could not care less.

I'd sooner programmers spent their time discussing algorithms, data structures, and test strategies.

Tony Ennis
So your version control system must be absolutely *inundated* with meaningless changes. That sounds pretty horrible.
Kirk Woll
It's never been an inconvenience - I don't really recur having a problem with extraneous noise. Further, my IDE's built-in CVS diff-er has an ignore white space option. /shrug And I could not care less about what the code manager generates internally. Ladies and germs, there are larger fish to fry. This is minutia.
Tony Ennis
@tony, The fun part comes when you need to locate when an offending change was made and the information your IDE gets from CVS is misleading.
Thorbjørn Ravn Andersen
All I can say is that I haven't had a problem with diff'ing code in 20 years.
Tony Ennis
+1  A: 

It's all a matter of choice really. If you find a method easier to read than the other than go ahead!

The only exception to this is when you are working on and contributing to a large scale project. In this scenario you will obviously have to follow the convention which is maintained throughout the rest of the source code.

I'm personally a fan on the first way and the majority of people follow this convention.

Adam
+1  A: 

Consistency is all important.

If you like the second style, stick with it. ( I do.)

BUT whatever style you eventually choose to use, do not change it in the middle of your code.

{edit] Netbeans has an option to display the code in your style of choice, IIRC.

slashmais
+1  A: 

This is more a religeous question, than a programming question. People have strong opinions about code formatting style. The first format does follow the style that Sun Microsystems has promoted, the second format follows what I like to call not-monkey style. As mentioned above, strong opinions abound concerning code formatting style.

As stated by one or more previous posters, companys use code formatters, so your preferred format style may not survive a checkin to source control.

Consistancy is important, but in a team of 6 programmers, if 5 goof rockets produce hard to read code, it may be a good idea to be inconsistant with them and, attempt, to produce not-hard to read code.

dwb
-1 for calling the pseudo-standard formatting "monkey style".
Douglas
@douglas, did he hurt your feelings? What about the technical content of his posting?
Tony Ennis
This is a social question, not a technical one. Both formatting styles compile fine. Calling people names (monkey-style programmers, "goof rockets") is likely to turn preferences into strong opinions and conflict, which is just a waste of time.
Douglas
I don't think Sun has credibility in code formatting. Just read JDK code, it's horrible.
irreputable
+6  A: 
  1. Decide on a single convention on the team (preferably a standard one in case you want to work with others later)
  2. Configure your and everybody elses IDE to use that format and that only.
  3. Make the reformat happen automatically and preferably at every Ctrl-S.

This will make all sources be uniform at all times, and ensure that changes in the source repository is actual changes and not just reformats at a later time.

For Eclipse this can be done by configuring the formatter (I happen like the defaults), and save the preferences which can then be loaded by everybody else. Also the Java -> Editor -> Save actions allow for automatic reformatting at every Ctrl-S, which is also a savable preference.

I've found with the above that an additional heuristic

  • Everything must fit on a single line

gives a lot of automatically triggered refactorings giving a lot of named locals which then capture intent by their naming, which in turn works well for debugging as you generally have more values in variables which show up in the debugger when single stepping, and you tend to have less opportunities for NullPointerExceptions on each line.


Edit: I wrote on my blog about this.

Thorbjørn Ravn Andersen
Great answer. Didn't know about the Eclipse "Save Actions". Very helpful. Thanks.
glanden
Actually I wouldn't suggest auto-formatting on every save - formatter is not perfect and can make some mess with human-made readable formating. Especially annotations.
gertas
@gertas, if that happens, your human does not comply to the official standard anyway. The whole point is that anybody Can reformat anytime without messing things up.
Thorbjørn Ravn Andersen
My point was that annotation part of formatter in Eclipse is terrible. I didn't check if it can be improved by configuration, but don't like it generally. I use selective formatting (Select code and format) and of course I obey Sun/Oracle standards.
gertas
@gertas, too errorprone to my taste. Perhaps you should have a look at the Eclipse formatter and see if it can be beaten into formatting as you like.
Thorbjørn Ravn Andersen
A: 

I disagree with your title. How is the 1st one standard and the 2nd one non-standard?

Preferences changes over time. We no longer program on 80*25 text terminals. We are writing different type of codes. The justification to save one line becomes more and more amusing.

@RequestMapping(value="/hotels/{hotel}/bookings/{booking}",
                method=RequestMethod.GET)
public String getBooking(
        @PathVariable("hotel") long hotelId, 
        @PathVariable("booking") long bookingId, 
        Model model) {                                    // WOW! I SAVED A LINE!
    Hotel hotel = hotelService.getHotel(hotelId);
    Booking booking = hotel.getBooking(bookingId);
    model.addAttribute("booking", booking);
    return "booking";
}
irreputable
The amount of code you can have on a single screen is still important. The more you can see, the less you have to scroll.
Thorbjørn Ravn Andersen
I have 1600 pixels vertically, it's too much!
irreputable
A: 

The answer is that it depends on the audience for the code. If only you will ever see the code, then you may do what you like. If others may see the code, then it depends on your social and/or professional relationship with them. If others might modify the code, then it would be unprofessional not to attempt to code in some standard way.

Steve Emmerson
A: 

Adopting the standard style as laid down by Sun over a decade ago will make it easier for people new to your organisation to get up to speed, it'll be code formatted in a way they've been used to during their prior careers.

Apart from that, any (well thought out) style will do as long as it is applied consistently (I've had a hall of a time figuring out inconsistently styled code, where different people working on it had employed different styles even while modifying existing methods).

jwenting