我不想浪费任何人的时间,直截了当。
以下哪个示例符合样式约定?
例 1
// creating components
JButton easyButton = new JButton("Easy");
JButton hardButton = new JButton("Hard");
// then containers
JPanel topPanel = new JPanel();
JPanel bottomPanel = new JPanel();
// then adding components to containers
topPanel.add(easyButton);
bottomPanel.add(hardButton);
例 2
// creating first container and all its components
JPanel topPanel = new JPanel();
JButton easyButton = new JButton();
topPanel.add(easyButton);
JPanel bottomPanel = new JPanel();
JButton hardButton = new JButton();
bottomPanel.add(easyButton);
工厂方法:
JPanel createButtonPanel(String buttonLabel) {
JPanel panel = new JPanel();
panel.add(new JButton(buttonLabel));
return panel;
}
因为这两个示例都重复代码,这违反了任何理智的约定。
为了提高
可读性,我的个人风格是将相关代码组合在一起,例如在您的第二个示例中。
以下是我认为是一个相关的例子:https://softwareengineering.stackexchange.com/questions/56585/where-do-you-declare-variables-the-top-of-a-method-or-when-you-need-them