|
正例:
- 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();
- }
- }
公有静态常量应该通过类会见
固然通过类的实例会见公有静态常量是应承的,可是轻易让人它误以为每个类的实例都有一个公有静态常量。以是,公有静态常量应该直接通过类会见。 (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|