|
反例:
- private void handle(String fileName) {
- BufferedReader reader = null;
- try {
- String line;
- reader = new BufferedReader(new FileReader(fileName));
- while ((line = reader.readLine()) != null) {
- ...
- }
- } catch (Exception e) {
- ...
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- ...
- }
- }
- }
- }
正例:
- private void handle(String fileName) {
- try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
- String line;
- while ((line = reader.readLine()) != null) {
- ...
- }
- } catch (Exception e) {
- ...
- }
- }
删除未使用的私有方法和字段
删除未使用的私有方法和字段,使代码更简洁更易维护。若有需要再使用,可以从历史提交中找回。
反例:
- public class DoubleDemo1 {
- private int unusedField = 100;
- private void unusedMethod() {
- ...
- }
- public int sum(int a, int b) {
- return a + b;
- }
- }
正例:
- public class DoubleDemo1 {
- public int sum(int a, int b) {
- return a + b;
- }
- }
删除未使用的局部变量
删除未使用的局部变量,使代码更简洁更易维护。
反例:
- public int sum(int a, int b) {
- int c = 100;
- return a + b;
- }
正例:
- public int sum(int a, int b) {
- return a + b;
- }
删除未使用的方法参数
未使用的方法参数具有误导性,删除未使用的方法参数,使代码更简洁更易维护。但是,由于重写方法是基于父类或接口的方法定义,即便有未使用的方法参数,也是不能删除的。
反例:
- public int sum(int a, int b, int c) {
- return a + b;
- }
(编辑:无锡站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|