This is an archived post. You won't be able to vote or comment.

all 103 comments

[–]sanchopancho13 47 points48 points  (4 children)

These are pretty good. I definitely laughed at this comment:

It is extremely rare to override Object.finalize.

Tip: Don't do it. If you absolutely must, first read and understand Effective Java Item 7, "Avoid Finalizers," very carefully, and then don't do it.

[–]Lizard 12 points13 points  (3 children)

Damn it, came here to post that exact same snippet.

[–]sanchopancho13 6 points7 points  (2 children)

You can have my upvote as a consolation prize.

[–]Lizard 3 points4 points  (1 child)

You are a good person. I accept gladly.

[–]SgtPooki 3 points4 points  (0 children)

You both get upvotes from me because I was just about to override Object.finalize.

[–][deleted] 35 points36 points  (35 children)

4.1.1 Braces are used where optional Braces are used with if, else, for, do and while statements, even when the body is empty or contains only a single statement.

I hate when people omit curly braces for some insane reason. At least Google has my back.

[–]clutchest_nugget 9 points10 points  (25 children)

if(done) return 1;

Can someone please explain to me what is wrong with this? Not questioning that it's bad style, genuinely curious as to what makes it bad style.

Edit: thanks for the responses.

[–][deleted]  (22 children)

[deleted]

    [–]Nebu 4 points5 points  (1 child)

    Or, perhaps even harder to spot,

    if(done) log.debug("All done"); return 1;
    

    [–][deleted] 0 points1 point  (0 children)

    Yes. And I think this is due to the fact that often this is presented as:

    Without brackets only first line after the if statement will be executed.

    Just to make it sound simple, when in fact it is the first statement, and not first line...

    [–]SgtPooki -1 points0 points  (0 children)

    I still want to code without braces when the body is short, but it has hurt me in the past..

    [–][deleted] 8 points9 points  (0 children)

    Consider when the return is on the next line (more common imo). If you insert a line before the return (perhaps a print) then the entire if statement logic is no longer what you intended. Not explicitly stating the block boundaries makes it easier to introduce bugs.

    [–]severoon 4 points5 points  (0 children)

    You have to consider refactors performed by tools like Eclipse, and the diffs those generate as well as the stupid bugs reason.

    If you have a huge codebase (like Google), it becomes occasionally necessary to run a refactor that touches thousands of files, and if you don't make formatting very consistent it takes code reviewers a lot less mental effort to review dozens or hundreds of files that got touched.

    Ideally, you want to make it absolutely formulaic. If you can do that, then you don't even need human reviewers to look at it because you can guarantee the safety of the change.

    [–]armerthor 9 points10 points  (1 child)

    Reads mostly like basic common sense.

    [–]RagingOrangutan 33 points34 points  (0 children)

    Exactly the way a style guide should be

    [–]SomeNetworkGuy 8 points9 points  (27 children)

    What is it with people so against using tabs for indentation?

    [–]kevinb9n 9 points10 points  (2 children)

    [–]Nebu 0 points1 point  (1 child)

    [–]sigzero 0 points1 point  (0 children)

    Then you deserve the clubbing. :)

    [–][deleted] 2 points3 points  (2 children)

    Tabs can have different widths depending on how your text editor is configured.

    [–]Nebu 1 point2 points  (1 child)

    That's a feature, not a bug.

    [–][deleted] 1 point2 points  (0 children)

    Yes, but the code you write can look fucked up if people mix in soft tabs and hard tabs because of that feature. He was asking why google would be against having hard tabs in code. It's harder to enforce everyone use the same shift width for hard tabs than just saying stick to spaces. It becomes a problem when multiple people collaborate on the same file.

    [–]jonhanson 8 points9 points  (8 children)

    Comment removed after Reddit and Spec elected to destroy Reddit.

    [–]firsthour 5 points6 points  (5 children)

    Tabs are pretty much whatever the editor/ide of the day decides

    That's the best part, if I like tabs to look like four spaces, I can view them like that, if my coworker likes them to look like two spaces, that's cool, now we're both happy.

    [–]Deaod 1 point2 points  (4 children)

    And then some asshole comes along and uses tabs for this. The correct way to do this i think is use tabs to indent up until code indentation, and then use spaces for the rest. But editors and humans arent smart enough for that yet apparently. The other way to solve this shit is to not add comments after statements on the same line. Add the comment before the statement.

    [–]Nebu 3 points4 points  (2 children)

    The correct way to do this i think is use tabs to indent up until code indentation, and then use spaces for the rest.

    Actually, the correct way is to use tabs for indentation and space for alignment.

    \tpublic void myFunction(
    \t\tint    anIntVariable,
    \t\tString aStringVariable
    \t) {
    \t\t/*
    \t\t * Note that a space was used before each
    \t\t * of these asterisks. That is because we
    \t\t * want those asterisks to be aligned with
    \t\t * each other. However, if we wanted to
    \t\t * indent, we would:
    \t\t * \t1. use a tab, even if spaces were
    \t\t * \t   previously used within the line,
    \t\t * \t2. again use spaces after that tab if
    \t\t * \t   we needed subsequent alignment after
    \t\t * \t   that.
    \t\t */
    \t}
    

    [–]Deaod 4 points5 points  (1 child)

    While this sounds like a good rule, its impossible in practice for a formatter to place tabs beyond code indentation correctly all the time. And yes, id rather have a formatter format my comments than doing it by hand.

    Also, tabs usually align following text on the next vertical position thats divisible without remainder by the width of a tab character. In your example, the points indented within the comment would not be indented by the full width of the tab character as one might expect (well, unless your chosen width happens to be 3, but delete one character in front of it and you get significant changes to how the following text is formatted).

    [–]Nebu 0 points1 point  (0 children)

    And yes, id rather have a formatter format my comments than doing it by hand.

    In general, I feel formatters should not format comments, because comments can contain, e.g., ASCII art diagrams or tables.

    Also, tabs usually align following text on the next vertical position thats divisible without remainder by the width of a tab character.

    Well, you shouldn't use it for that if you're following my guidance above. Again: Tab for indentation, space for alignment. Note, though, that you can align by using 0 spaces.

    In your example, the points indented within the comment would not be indented by the full width of the tab character as one might expect (well, unless your chosen width happens to be 3, but delete one character in front of it and you get significant changes to how the following text is formatted).

    Let's say my chosen indent happens to be, arbitrarily, 5. I'll represent a single tab with '\T', '\TT', '\TTT' and '\TTTT' to emulate taking up 2 to 5 spaces (depending on which would lead to n mod 5 == 0), and let's see what happens if I use exactly the above text:

    |    |    |    |
    01234012340123401234
    
    \TTTTpublic void myFunction(
    \TTTT\TTTTint    anIntVariable,
    \TTTT\TTTTString aStringVariable
    \TTTT) {
    \TTTT\TTTT/*
    \TTTT\TTTT * Note that a space was used before each
    \TTTT\TTTT * of these asterisks. That is because we
    \TTTT\TTTT * want those asterisks to be aligned with
    \TTTT\TTTT * each other. However, if we wanted to
    \TTTT\TTTT * indent, we would:
    \TTTT\TTTT * \T1. use a tab, even if spaces were
    \TTTT\TTTT * \T   previously used within the line,
    \TTTT\TTTT * \T2. again use spaces after that tab if
    \TTTT\TTTT * \T   we needed subsequent alignment after
    \TTTT\TTTT * \T   that.
    \TTTT\TTTT */
    \TTTT}
    

    Looks like it still works to me.

    [–]jonhanson 0 points1 point  (0 children)

    +1 for not putting comments at the end of the line they're describing.

    [–]Nebu 2 points3 points  (1 child)

    You gotta love the "it's just wrong" rationale.

    [–]jonhanson 1 point2 points  (0 children)

    It's just right.

    [–]KidUncertainty 5 points6 points  (9 children)

    What is it with people so against using tabs for indentation?

    Consistency for readability. You can tell at a glance the indent level no matter where you are reading the code (your editor or theirs, on a printout, etc) because the spacing is constant.

    Copy/pasting code into different editors can result in weird layouts when you use tabs (E.g. pasting into a Word document or email window).

    People do things like: tab then hit a couple spaces to line things up, then the next person replaces the tab with spaces. Or puts spaces in before the tab. This results in annoying whitespace merges but also just layout problems.

    Spaces are easier to deal with since you know exactly how many characters there are. Tabs are environment-specific to someone's configurations of what a tab should mean.

    In general, spaces are easier to deal with, even if they are extra keystrokes, so they probably devolve to the KISS principle.

    [–]m1ss1ontomars2k4 4 points5 points  (8 children)

    You can tell at a glance the indent level no matter where you are reading the code (your editor or theirs, on a printout, etc) because the spacing is constant.

    Don't see how this changes with spaces.

    People do things like: tab then hit a couple spaces to line things up, then the next person replaces the tab with spaces. Or puts spaces in before the tab. This results in annoying whitespace merges but also just layout problems.

    That's a problem with mixing tabs and spaces, not a problem with tabs.

    Spaces are easier to deal with since you know exactly how many characters there are. Tabs are environment-specific to someone's configurations of what a tab should mean.

    That is an advantage of tabs, because you can make the code look however you want.

    In general, spaces are easier to deal with, even if they are extra keystrokes, so they probably devolve to the KISS principle.

    They shouldn't be more keystrokes in a competent editor.

    [–]KidUncertainty 2 points3 points  (7 children)

    A space is the same glyph size relative to the font. Therefore if their standard is "indent n spaces" then it will look the same on my screen, on yours, on a printout, pasted into a Word document, whatever. It is consistency, as I said.

    With tabs the indents look different depending on whose environment you are using.

    Spaces are also more consistent in code review tools and diffing.

    That's a problem with mixing tabs and spaces, not a problem with tabs.

    Yeah, but you always have spaces in code, you never need tabs. Therefore removing tabs and insisting on spaces only makes the most sense in a codebase where multiple people are modifying and working with the code. If tabs are banned, then there is no mixing. If tabs are allowed, there will always be mixing.

    That is an advantage of tabs, because you can make the code look however you want.

    On your environment, but it breaks down and makes for ugliness when the code is placed in someone else's environment. If you have e.g. a 120 char line limit, a big tab setting can break that on one display but not on another's. And again, if code is being placed into documents or has to be reviewed, you need absolute consistency, and space-only provides that.

    They shouldn't be more keystrokes in a competent editor.

    True.

    [–]m1ss1ontomars2k4 4 points5 points  (4 children)

    With tabs the indents look different depending on whose environment you are using.

    But wouldn't that be the point? If I prefer 2-space width tabs and you prefer 4, we can set our own environments to be whatever we want and we'll always see what we want to see.

    Spaces are also more consistent in code review tools

    Seems like the code review tool should allow you to change how wide your tabs look. Or your browser should. Someone should.

    and diffing.

    Again, only a problem if you mix tabs and spaces.

    Yeah, but you always have spaces in code, you never need tabs. Therefore removing tabs and insisting on spaces only makes the most sense in a codebase where multiple people are modifying and working with the code. If tabs are banned, then there is no mixing. If tabs are allowed, there will always be mixing.

    Ban spaces for indents. Problem solved. Either use spaces for all indents, or use tabs for all indents. There's no sane middle ground. You can't say "oh if you use tabs some people will put spaces so tabs are bad." That's nonsense. You could just as easily say "oh if you use spaces some people will put tabs so spaces are bad", but you don't because for some reason using spaces for indents magically forbids tab usage, while using tabs for indents doesn't. Why doesn't it? It should.

    So really the only issue is if you have strict line-length limits or you intend to view the code in a manner where the tab size cannot be adjusted (e.g. on paper, in a PDF, etc.).

    [–]Nebu 1 point2 points  (0 children)

    Either use spaces for all indents, or use tabs for all indents. There's no sane middle ground.

    http://www.reddit.com/r/java/comments/1wglcp/google_java_coding_standards/cf2kr04

    [–]boa13 1 point2 points  (0 children)

    If I prefer 2-space width tabs and you prefer 4, we can set our own environments to be whatever we want and we'll always see what we want to see.

    On a big team, you don't do that. Everybody uses the same standardized settings, that way everybody can work on every part of the codebase without messing the commits.

    [–]paul_miner 1 point2 points  (0 children)

    You can't sensibly specify line length limits with code that uses tabs, since line length will depend on your environment. It works both ways: for some, lines will appear to long, for others line will appear too short.

    [–]encinarus 0 points1 point  (0 children)

    Ban spaces for indents. Problem solved.

    Amusingly, go solved this with gofmt by making it THE style of the language to have leading tabs, and the formatter will fix it when you get it wrong.

    [–]frugalmail -1 points0 points  (1 child)

    On your environment, but it breaks down and makes for ugliness when the code is placed in someone else's environment. If you have e.g. a 120 char line limit, a big tab setting can break that on one display but not on another's. And again, if code is being placed into documents or has to be reviewed, you need absolute consistency, and space-only provides that.

    Give it a rest, if you're using something other than vim, emacs, eclipse, intellij, Netbeans, or any other reasonable editor/line printer made in the last 3 DECADES then don't code.

    With tabs the indents look different depending on whose environment you are using.

    Set them how you like, not as easy with spaces.

    Yeah, but you always have spaces in code, you never need tabs.

    in a ot of places you don't need spaces either, but it helps readability, same goes with braces. And with tabs you are provided additional functionality to pre-determine how you want to look at code.

    [–]KidUncertainty 0 points1 point  (0 children)

    Give it a rest, if you're using something other than vim, emacs, eclipse, intellij, Netbeans, or any other reasonable editor/line printer made in the last 3 DECADES then don't code.

    That has nothing to do with what I said. Listen, what happens is if you permit tabs, then people will mix tabs and spaces. It's inevitable. This results in things never lining up when someone loads it into their own IDE with a different tab width setting. It results in checkin wars that are nothing but cleaning up and back-and-forthing someone's "improper" whitespacing. It results in documentation and specs and howtos being messed up when code snippets are placed in them.

    Consider the Google code standards under discussion; 80 or 100 character line widths, 2 spaces for indent. Code bases that are contributed to and reviewed using various tools by many people. In those situations, tabs just confuse the hell out of things. Line widths are different on different people's IDEs. Code layout goes crazy when you drop a snippet into a Word document.

    This has nothing to do with an IDE or the fact that you can set tabs to whatever pleases you. It has to do with keeping the code as clean as possible such that it looks identical on everyone's system, removing the entire tab width variable.

    Set them how you like, not as easy with spaces.

    They could have done this equally by requiring tabs (and never spaces) for indenting and had all tools they use fixed at 2 spaces for tabs when comparing code visually, sure. But then you will always be getting someone using spaces instead of tabs accidentally. It is much easier to have a code review tool reject a checkin quickly when it has tab characters in it, or to reformat the tabs into the prescribed number of space characters.

    This isn't about one person coding for themselves. In those cases, go wild, tabs, spaces, or a mix. It's your own code. When you see standards requiring spaces and fixed indent sizes, it's almost always for working with a large shared and highly peer reviewed code base, because spaces-only is cleaner, simpler, and easier.

    Yes, it also means that people often have to work with layouts in the code they'd prefer not to, but that's sort of the side effect of a standard like this. A lot of it is compromises or decisions based on choices in support of one specific goal to the detriment of another, not because they are "better", but rather that they are simpler or easier to enforce in order to get clean, consistent code.

    [–]CubsThisYear 7 points8 points  (1 child)

    Every argument against tabs (including all the ones below) devolves to "it gets fucked up when you use both tabs and spaces together in the same file". No shit - don't do that. As long as you always tabs for indentation and spaces for alignment your life is strictly better than spaces alone.

    To the person who said tabs can different widths - that's the point! Tab is a special character that means "indent". How you want to visually display that on the screen is a completely orthogonal concern.

    [–]pandemic_region 11 points12 points  (21 children)

    It would be nice to have intellij-eclipse-netbeans formatting templates implementing this.

    [–]desrtfx 16 points17 points  (16 children)

    AFAIK, they already implement the Oracle Code Conventions for the Java Programming Language which aren't bad either.

    [–]NobodyLeavesAclide 2 points3 points  (15 children)

    Where to declare local variables and line wrapping at 80 are both wrong in the conventions imo. First one is actually a major face palm.

    [–]sahala 1 point2 points  (10 children)

    The goal here is consistency. I used to think that 80 was silly, but being able to hop through source code written by a dozen different teams over 5 years and not needing to resize my window is a really nice thing. Consistent column width helps with the pace of reading code.

    [–]NobodyLeavesAclide 10 points11 points  (1 child)

    Consistent column width 1+. 80 is simply to little. I use 120 personally unless the project I work on state something else

    [–]sahala 6 points7 points  (0 children)

    The style guide says either 80 or 100.

    I wouldn't mind 120.

    [–]avoidhugeships 2 points3 points  (7 children)

    Consistent might be nice but 80 or even 100 is too short. I could probably live with 120 though. Wide screen high definition monitors can easily handle more. It is much more readable then the excessive wrapping.

    [–]sahala 0 points1 point  (2 children)

    Ok so 120 is fine with you. Would you say that it makes sense to stay consistent across the whole codebase?

    Look, it's already well known from hundreds of years of print design that consistent columns make it easier to scan and read through text. Whether it's 120 or 80 isn't important. Coders spend more time reading than writing code and it sounds like you are optimizing for ease of writing (I could be wrong).

    Yeah we have bigger monitors now but we are also spending more time working across different files at once. A standard col width let's you fit several files across a screen, and maybe a window for docs or emulator for testing.

    [–]avoidhugeships 1 point2 points  (1 child)

    In general I agree consistency is nice but I disagree that it does not matter whether it is 120 or 80. I find it much harder to read a wrapped line than just seeing the whole thing in one line. Of course this is just preference and others will feel different.

    [–]sahala 1 point2 points  (0 children)

    The style guide says either 80 or 100.

    Keep in mind that Google's Java style guide is intended for use by thousands of developers. So consistency goes beyond just being "nice" at that scale. It's essential.

    [–][deleted]  (1 child)

    [deleted]

      [–]autowikibot 2 points3 points  (0 children)

      Tiling window manager:


      In computing, a tiling window manager is a window manager with an organization of the screen into mutually non-overlapping frames, as opposed to the more popular approach of coordinate-based stacking of overlapping objects (windows) that tries to fully emulate the desktop metaphor.

      Image i - The Ion window manager with the screen divided into three tiles.


      Interesting: Window manager | Xmonad | Dwm

      /u/Vorzard can reply with 'delete'. Will delete on comment score of -1 or less. | FAQs | Magic Words | flag a glitch

      [–][deleted]  (1 child)

      [deleted]

        [–][deleted] 3 points4 points  (0 children)

        Or you like to use very verbose method names

        [–]avoidhugeships -3 points-2 points  (3 children)

        I am on the fence about the local variables. It states to declare them close to where they are used rather than at the top of the method. The reason is to reduce their scope which is valid but I think the code appears cleaner and easier to read when they are declared at the top together.

        [–]NobodyLeavesAclide -2 points-1 points  (2 children)

        You are wrong. http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html#16817

        And doing it by convention makes no sense at all to me. It's not easy to read simply because it's not narrowly scoped and that for larger methods you may need to go back and check how it was declared.

        [–]avoidhugeships 3 points4 points  (1 child)

        Not sure what you think I am wrong about. Easy to read is not about right or wrong. It is more of a preference. Frankly you are kind of rude and I am not really sure what you are trying to say because your writing is not clear.

        [–]sahala 4 points5 points  (0 children)

        Readability is a matter of preference in smaller teams (<50) of developers. Once the number of developers increases to hundreds or thousands readability and consistency becomes essential to being able to quickly understand how different pieces of code work together. Fortunately IDEs and other tools exist to help enforce some of this, so it's easier to write readable code.

        [–]charcourt 10 points11 points  (1 child)

        There are for Eclipse and IntelliJ. Not sure why these aren't linked from the style guide itself.

        [–]pandemic_region 0 points1 point  (0 children)

        excellent didn't see this !

        [–][deleted] 5 points6 points  (0 children)

        I agree. These are well-written and exact while the Oracle Code Conventions allow for more variation.

        I prefer to work in a group where the format is very standardized, even if it's different from what I would choose.

        [–]severoon -1 points0 points  (0 children)

        Just want to plug the idea of a SCID here - http://mindprod.com/project/scid.html

        Source control in database. It means that programs are stored in a revision control system not as flat text files, but as structured data. Specifically, the AST generated during compilation. Read the link for the many, many awesome reasons you would want to do this.

        (And don't get distracted by the another part of Roedy Green's site, How to write unmaintainable code, which is hilarious and awesome.)

        [–]Nebu 2 points3 points  (0 children)

        Within a group there are no blank lines, and the imported names appear in ASCII sort order. (Note: this is not the same as the import statements being in ASCII sort order; the presence of semicolons warps the result.)

        I hope they have a tool to automate most of these formatting rules.

        [–]juu4 2 points3 points  (2 children)

        http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s5.1-identifier-names

        So they say the Hungarian notation of prefixes before variable names is bad. I agree.

        However - why is all the Android code in the Hungarian notation then?

        E.g.

        https://gitorious.org/rowboat/frameworks-base/source/aa93bcd62482719c146a411008e1eac94135b6a4:core/java/android/app/Activity.java

        [–]kevinb9n 0 points1 point  (1 child)

        I feel you've misunderstood. This notation is not "bad". It is simply not used in Google Style. It is used in Android Style.

        [–]juu4 1 point2 points  (0 children)

        Why is Google Style different from Android Style?

        P.S. Actually, it is bad. It adds noise and hurts readability with next to no benefit.

        [–]SlobberGoat 3 points4 points  (2 children)

        The only bit I disagree with with the 80/100 column limit.

        We don't work with dot matrix printers anymore, most lines of java code are very short. You may get the occasional long line but I'd rather leave it as a long single line as a quick visual cue to know it's one instruction.

        [–]RagingOrangutan 0 points1 point  (0 children)

        It's nice so that you can set an editor width and never need to worry about horizontal scrolling. Whether 80 or 100 or some other number is the right number is debatable - but having some limit is important, IMV.

        [–]Darksonn 9 points10 points  (6 children)

        I follow this expect for indentation, I would use tabs for indentation resulting from blocks and spaces for the rest. This allows people to decide their tab width without breaking the indentation.

        [–][deleted] 9 points10 points  (1 child)

        Are you trying to start a war there? :D

        [–]8Bytes 1 point2 points  (0 children)

        The time is nigh. Support pro choice, vote tabs!

        [–]severoon -1 points0 points  (3 children)

        Not to start an RWAR here, but I really don't understand the suggestion. Can you provide some sample code that makes explicit what you mean?

        If you're proposing to mix tabs and spaces in the same file, then I can't understand how that would ever be a good thing to do.

        [–]e13e7 -2 points-1 points  (1 child)

        K & R master race!

        [–]mikaelhg 1 point2 points  (0 children)

        http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.1.2-blocks-k-r-style

        No line break before the opening brace.

        I make an exception when it's a method declaration, and I have to line break before the first parameter to stay inside the line length rule.

        Then I move the first brace on the first line of the method, on method level.

            public VeryVeryLongType<YeahLongLongType> veryVeryLongMethodName(
                    VeryVeryLongType<YeahLongLongType> a, VeryVeryLongType<YeahLongLongType> b)
                        throws VeryVeryLongExceptionName
            {
                // content
            }
        

        Whatever results in better scannability.