简体   繁体   English

冒险选择非标准的Java代码缩进样式?

[英]Risky to choose a non-standard Java code indentation style?

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? 我发现这更容易阅读,但如果我使用这种风格,我会遇到与他人合作的问题吗?

  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. 配置您和所有人的 IDE以使用该格式。
  3. Make the reformat happen automatically and preferably at every Ctrl-S. 使重新格式化自动发生,最好是每个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 to like the defaults), and save the preferences which can then be loaded by everybody else. 对于Eclipse,这可以通过配置格式化程序(我碰巧喜欢默认值)来完成,并保存首选项,然后可以由其他人加载。 Also the Java -> Editor -> Save actions allow for automatic reformatting at every Ctrl-S, which is also a savable preference. 此外,Java - >编辑器 - >保存操作允许在每个Ctrl-S上自动重新格式化,这也是一个可爱的偏好。

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. 给出了很多自动触发的重构,给出了许多命名的本地,然后通过命名捕获意图,这反过来又适用于调试,因为你通常在单步执行时在调试器中显示更多的变量值,并且你倾向于每行的NullPointerExceptions机会较少。


Edit: I wrote on my blog about this . 编辑: 我在我的博客上写到这一点


Edit 2014-08-19: It appears that if the Eclipse formatter settings are saved to a file, IntelliJ IDEA can format source using that file. 编辑2014-08-19:似乎如果将Eclipse格式化程序设置保存到文件,IntelliJ IDEA可以使用该文件格式化源。

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. 您应该查看您的直接项目之外的代码,程序员移动,公司被收购,工具将倾向于为标准配置,等等。

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. 通常这涉及无休止的讨论,但我想这里列出的2个是更常见的。

It doesn't matter. 没关系。 Most companies use a code formatter anyways. 大多数公司无论如何都使用代码格式化程序。

I also prefer the second style. 我也更喜欢第二种风格。

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. PS - 我和你在一起:我更喜欢在下一行上戴上牙套。 The Sun convention is the first one. 太阳会议是第一次。 It's better for book authors, because there's less white space. 这对书籍作者来说更好,因为空白较少。

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. 当我必须修改代码时,我使用IDE的代码格式化器重新格式化文件,使用默认值。 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. 我很快就会把程序员花在讨论算法,数据结构和测试策略上。

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. 我们不再编程80 * 25文本终端。 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";
}

与代码格式化一样,如果您与喜欢另一个人的人合作,则存在风险。

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. 我个人是第一种方式的粉丝,大多数人都遵循这个惯例。

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. {edit] Netbeans可以选择以您选择的方式显示代码,IIRC。

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. 第一种格式遵循Sun Microsystems推出的风格,第二种格式遵循我喜欢称之为非猴子风格的格式。 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. 一致性是重要的,但是在一个由6名程序员组成的团队中,如果5个火箭弹产生难以阅读的代码,那么与它们不一致并试图产生难以阅读的代码可能是一个好主意。

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. 如果其他人可能会修改代码,那么不尝试以某种标准方式编写代码是不专业的。

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. 采用Sun十多年前制定的标准风格将使新组织的人们更容易加快速度,它将以他们在以前的职业生涯中习惯的方式进行代码格式化。

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). 除此之外,任何(经过深思熟虑的)风格都会一直使用(我有一段时间来确定代码不一致的代码,不同的人在使用不同的风格时,即使在修改现有代码时也是如此方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM