加入收藏 | 设为首页 | 会员中心 | 我要投稿 厦门站长网 (https://www.0592zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 运营中心 > 建站资源 > 优化 > 正文

消灭 Java 代码的“坏味道”

发布时间:2019-10-12 06:35:10 所属栏目:优化 来源:王超
导读:副标题#e# 代码中的坏味道,如私欲如灰尘,每天都在增加,一日不去清除,便会越累越多。如果用功去清除这些坏味道,不仅能提高自己的编码水平,也能使代码变得精白无一毫不彻。这里,一直从事Java研发相关工作的阿里高级地图技术工程师王超,整理了日常工作

反例:

  1. private void handle(String fileName) { 
  2.     BufferedReader reader = null; 
  3.     try { 
  4.         String line; 
  5.         reader = new BufferedReader(new FileReader(fileName)); 
  6.         while ((line = reader.readLine()) != null) { 
  7.             ... 
  8.         } 
  9.     } catch (Exception e) { 
  10.         ... 
  11.     } finally { 
  12.         if (reader != null) { 
  13.             try { 
  14.                 reader.close(); 
  15.             } catch (IOException e) { 
  16.                 ... 
  17.             } 
  18.         } 
  19.     } 

正例:

  1. private void handle(String fileName) { 
  2.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 
  3.         String line; 
  4.         while ((line = reader.readLine()) != null) { 
  5.             ... 
  6.         } 
  7.     } catch (Exception e) { 
  8.         ... 
  9.     } 

删除未使用的私有方法和字段

删除未使用的私有方法和字段,使代码更简洁更易维护。若有需要再使用,可以从历史提交中找回。

反例:

  1. public class DoubleDemo1 { 
  2.     private int unusedField = 100; 
  3.     private void unusedMethod() { 
  4.         ... 
  5.     } 
  6.     public int sum(int a, int b) { 
  7.         return a + b; 
  8.     } 

正例:

  1. public class DoubleDemo1 { 
  2.     public int sum(int a, int b) { 
  3.         return a + b; 
  4.     } 

删除未使用的局部变量

删除未使用的局部变量,使代码更简洁更易维护。

反例:

  1. public int sum(int a, int b) { 
  2.     int c = 100; 
  3.     return a + b; 

正例:

  1. public int sum(int a, int b) { 
  2.     return a + b; 

删除未使用的方法参数

未使用的方法参数具有误导性,删除未使用的方法参数,使代码更简洁更易维护。但是,由于重写方法是基于父类或接口的方法定义,即便有未使用的方法参数,也是不能删除的。

(编辑:厦门站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!