|
正例:
- public int sum(int a, int b) {
- return a + b;
- }
删除表达式的多余括号
对应表达式中的多余括号,有人认为有助于代码阅读,也有人认为完全没有必要。对于一个熟悉 Java 语法的人来说,表达式中的多余括号反而会让代码显得更繁琐。
反例:
- return (x);
- return (x + 2);
- int x = (y * 3) + 1;
- int m = (n * 4 + 2);
正例:
- return x;
- return x + 2;
- int x = y * 3 + 1;
- int m = n * 4 + 2;
工具类应该屏蔽构造函数
工具类是一堆静态字段和函数的集合,不应该被实例化。但是,Java 为每个没有明确定义构造函数的类添加了一个隐式公有构造函数。所以,为了避免 java "小白"使用有误,应该显式定义私有构造函数来屏蔽这个隐式公有构造函数。
反例:
- public class MathUtils {
- public static final double PI = 3.1415926D;
- public static int sum(int a, int b) {
- return a + b;
- }
- }
正例:
- public class MathUtils {
- public static final double PI = 3.1415926D;
- private MathUtils() {}
- public static int sum(int a, int b) {
- return a + b;
- }
- }
删除多余的异常捕获并抛出
用 catch 语句捕获异常后,什么也不进行处理,就让异常重新抛出,这跟不捕获异常的效果一样,可以删除这块代码或添加别的处理。
反例:
- private static String readFile(String fileName) throws IOException {
- try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
- String line;
- StringBuilder builder = new StringBuilder();
- while ((line = reader.readLine()) != null) {
- builder.append(line);
- }
- return builder.toString();
- } catch (Exception e) {
- throw e;
- }
- }
正例:
- private static String readFile(String fileName) throws IOException {
- try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
- String line;
- StringBuilder builder = new StringBuilder();
- while ((line = reader.readLine()) != null) {
- builder.append(line);
- }
- return builder.toString();
- }
- }
公有静态常量应该通过类访问
虽然通过类的实例访问公有静态常量是允许的,但是容易让人它误认为每个类的实例都有一个公有静态常量。所以,公有静态常量应该直接通过类访问。 (编辑:我爱故事小小网_铜陵站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|