【重构】代码优化通用方法

star2017 1年前 ⋅ 640 阅读

很多有问题的代码都可以通过这些方法进行优化,快来看看你的代码是否需要优化?

避免使用空块

坏味道代码

public class EmptyBlockBefore {
    public static void method(boolean isTrue) {
        if (isTrue) ;
        System.out.println("before");
    }

    public static void method2(boolean para) {
        boolean isTrue = para;
        {
        }
        if (isTrue) {
        }
        System.out.println("before");
    }

    public static void method3() {
        try {
            int in = System.in.read();
            System.out.println(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}

修改后代码

public class EmptyBlockAfter {
    public static void method(boolean isTrue) {
        if (isTrue) {
            System.out.println("before");
        }
    }

    public static void method2(boolean isTrue) {
        if (isTrue) {
            //TODO 待补充
        }
        System.out.println("before");
    }

    public static void method3() {
        try {
            int in = System.in.read();
            System.out.println(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

避免使用空类

坏味道代码

public class EmptyClassBefore {
}

这种类就直接把他删除

去掉多余的import

坏味道代码

import java.io.IOException;
import java.lang.*;
public class ExcessImportBefore {
    public static void main(String[] args) {
        System.out.println("去掉多余的import");
    }
}

修改后代码

package com.cimu.common;
public class ExcessImportAfter {
    public static void main(String[] args) {
        System.out.println("去掉多余的import");
    }

}

剪切无效代码

坏味道代码

public class CutInvalidCodeBefore {
    private String name;
    public static void method(){
        int i;
        method2("test",null);
    }

    private static void method2(String str1,String str2) {
        System.out.println(str1);
    }

    private static void method3(String str1,String str2) {
        System.out.println(str1);
    }
}
class TestClass{
    private static void test(String str1,String str2){
        System.out.println(str1);
    }
}

修改后的代码

public class CutInvalidCodeAfter {
    public static void method(){
        method2("test");
    }
    private static void method2(String str1) {
        System.out.println(str1);
    }
}

方法命名

方法命名小技巧:就是可以首先考虑应该给这个方法写上一句怎样的注释,然后想办法将注释变成方法名称。

坏味道代码

public class MethodNamedBefore {
    private static String s;
    public static void method(){
        s="test";
        System.out.println(s);
    }
}

修改后的代码

public class MethodNamedAfter {
    private static String name;
    public static void method(){
        name="test";
        System.out.println(name);
    }
}

去掉重复代码

坏味道代码

public class DeleteDuplicateCodeBefore {
   public static void method(){
        printName("张三");
        printDepart("研发中心");
   }
    public static void printName(String name){
        System.out.println(name);
    }
    public static void printDepart(String depart){
        System.out.println(depart);
    }
}

修改后代码

public class DeleteDuplicateCodeAfter {
    public static void method(){
        printContent("张三");
        printContent("研发中心");
    }
    public static void printContent(String content){
        System.out.println(content);
    }
}

如何优雅使用switch语句

坏味道代码

ublic class GraceUseSwitchBefore {
    public static void method(int count){
        switch (count){
            case 0 :
                System.out.println("0");
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
        }
    }
}

修改后代码

public class GraceUseSwitchAfter {
    public static void method(int count){
        switch (count){
            case 0 :
                System.out.println("0");
                break;
            case 1:
                System.out.println("1");
                break;
            case 2:
                System.out.println("2");
                break;
            default:
                System.out.println("d");
                break;
        }
    }
}

用大写L代替小写l定义long变量

坏味道代码

public class UseUpperLongBefore {
    public static void method(int count){
        long l=1l;
        System.out.println(l);
    }
}

修改后代码

public class UseUpperLongAfter {
    public static void method(int count){
        long l=1L;
        System.out.println(l);
    }
}

避免在一条语句中声明或赋值多个变量

坏味道代码

public class DefinitionMoreVariableBefore {
    public static void method(int count){
        long long1,long2;
        long1 = long2 = 1L;
        System.out.println(long1);
        System.out.println(long2);
    }

}

修改后代码

public class DefinitionMoreVariableAfter {
    public static void method(int count) {
        long long1 = 1L;
        long long2 = 1L;
        System.out.println(long1);
        System.out.println(long2);
    }

}

去掉控制标志的临时变量

坏味道代码

public class DelTempFlagBefore {
    public static void method() {
        System.out.println(getLevel(1));
    }
    public static String getLevel(int type) {
        String resultData = "";
        if (type == 1) {
            resultData = "第一";
        } else if (type == 2) {
            resultData = "第二";
        } else {
            resultData = "第三";
        }
        return resultData;
    }
}

修改后代码

public class DelTempFlagAfter {
    public static void method() {
        System.out.println(getLevel(1));
    }
    public static String getLevel(int type) {
        String resultData = "";
        if (type == 1) {
            return "第一";
        } else if (type == 2) {
            return "第二";
        } else {
            return "第三";
        }
    }
}

避免赋予临时变量过多的角色

坏味道代码

public class MoreTempFlagBefore {
    public static void method() {
        String temp;
        temp = "it is " + getType();
        System.out.println(temp);
        temp = "this is " + getName();
        System.out.println(temp);
    }

    private static String getName() {
        return "张三";
    }

    private static String getType() {
        return "aaaa";
    }
}

修改后代码

public class MoreTempFlagAfter {
    public static void method() {
        String tempType = "";
        String tempName = "";
        tempType = "it is " + getType();
        System.out.println(tempType);
        tempName = "this is " + getName();
        System.out.println(tempName);
    }

    private static String getName() {
        return "张三";
    }

    private static String getType() {
        return "aaaa";
    }
}

避免使用魔法数字

坏味道代码

public class NotUseNumBefore {
    public static void method(int type) {
        if (type == 3) {
            System.out.println("3");
        } else if (type == 4) {
            System.out.println("4");
        }
    }
}

修改后代码

public class NotUseNumAfter {
    public static void method(int type) {
        if (type == Consts.NUM_3) {
            System.out.println("3");
        } else if (type == Consts.NUM_4) {
            System.out.println("4");
        }
    }
}
class Consts {
    public static int NUM_3 = 3;
    public static int NUM_4 = 4;
}

在for循环内修正增量因子有什么弊端

坏味道代码

public class ForUpdateDivisorBefore {
    public static void method(int count){
        for (int i = 0; i < 10;) {
            i = i+1;
            System.out.println(i);
        }
    }
}

修改后代码

public class ForUpdateDivisorAfter {
    public static void method(int count){
        for (int i = 0; i < 10;i+=1) {
            System.out.println(i);
        }
    }
}

用Enum代替Integer类型码常量

坏味道代码

public class UseEnumBefore {
    public static String getDayName(int type) {
        if (WeekConsts.WEEK_MONDAY == type) {
            return "周一";
        } else if (WeekConsts.WEEK_TUESDAY == type) {
            return "周二";
        } else if (WeekConsts.WEEK_WEDNESDAY == type) {
            return "周三";
        } else if (WeekConsts.WEEK_THURSDAY == type) {
            return "周四";
        } else if (WeekConsts.WEEK_FRIDAY == type) {
            return "周五";
        } else if (WeekConsts.WEEK_SATURDAY == type) {
            return "周六";
        } else {
            return "周日";
        }
    }
}

class WeekConsts {
    public static final Integer WEEK_SUNDAY = 0;
    public static final Integer WEEK_MONDAY = 1;
    public static final Integer WEEK_TUESDAY = 2;
    public static final Integer WEEK_WEDNESDAY = 3;
    public static final Integer WEEK_THURSDAY = 4;
    public static final Integer WEEK_FRIDAY = 5;
    public static final Integer WEEK_SATURDAY = 6;
}

修改后代码

public class UseEnumAfter {
    public static String getDayName(WeekEnum type) {
        if (WeekEnum.MONDAY == type) {
            return "周一";
        } else if (WeekEnum.TUESDAY == type) {
            return "周二";
        } else if (WeekEnum.WEDNESDAY == type) {
            return "周三";
        } else if (WeekEnum.THURSDAY == type) {
            return "周四";
        } else if (WeekEnum.FRIDAY == type) {
            return "周五";
        } else if (WeekEnum.SATURDAY == type) {
            return "周六";
        } else {
            return "周日";
        }
    }

}
enum WeekEnum{
    SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY ,SATURDAY
}

用BigDecimal类型进行精确计算

坏味道代码

public class UseBigDecimalBefore {
    public static void method(int count){
        System.out.println(99.00-88.90);
    }

}

修改后代码

public class UseBigDecimalAfter {
    public static void method(int count){
        BigDecimal b1 = new BigDecimal("99.00");
        BigDecimal b2 = new BigDecimal("88.90");
        NumberFormat nf = new DecimalFormat("#.##");
        System.out.println(nf.format(b1.subtract(b2)));
    }
}

避免混用“+”

坏味道代码

public class NotUsePlusBefore {
    public static void method(int count){
        System.out.println("2+4="+2+4);
    }
}

修改后代码

public class NotUsePlusAfter {
    public static void method(int count){
        int result = 2+4;
        System.out.println("2+4="+result);
    }
}

避免混用复杂运算符

坏味道代码

public class NotUseComplexCalcBefore {
    public static void method(int times) {
        System.out.println(20 + getScore() * times > 100);
    }
    private static int getScore() {
        return 10;
    }
}

修改后代码

public class NotUseComplexCalcAfter {
    public static void method(int times) {
        int totalScore = 20 + getScore() * times;
        System.out.println(totalScore > 100);
    }
    private static int getScore() {
        return 10;
    }
}

避免使用复杂条件式或分支

坏味道代码1

public class NotUseComplexConditionOneBefore {
    public static void method() {
        //是否幸福 月入大于2000
        if (getBaseMoney("1") + getBonus(205) - getTax("") - 1000 > 2000) {
            System.out.println("开心");
        }
    }

    private static int getTax(String type) {
        if ("1".equals(type)) {
            return 200;
        }
        return 300;
    }

    private static int getBonus(int workTime) {
        if (workTime > 200) {
            return 1000;
        }
        return 0;
    }

    private static int getBaseMoney(String type) {
        if ("1".equals(type)) {
            return 2000;
        }
        return 4000;
    }

}

修改后代码1

public class NotUseComplexConditionOneAfter {
    public static void method() {
        //是否幸福 月入大于2000
        int noTaxMoney = getBaseMoney("1") + getBonus(205) - getTax("1") - 1000;
        if (noTaxMoney > 2000) {
            System.out.println("开心");
        }
    }

    private static int getTax(String type) {
        if ("1".equals(type)) {
            return 200;
        }
        return 300;
    }

    private static int getBonus(int workTime) {
        if (workTime > 200) {
            return 1000;
        }
        return 0;
    }

    private static int getBaseMoney(String type) {
        if ("1".equals(type)) {
            return 2000;
        }
        return 4000;
    }

}

坏味道代码2

public class NotUseComplexConditionTwoBefore {
    public static int getInsurance(String type) {
        int result = 0;
        if ("1".equals(type)) {
            //死亡
            result = 1000000;
        } else {
            //失业
            if ("2".equals(type)) {
                result = 50000;
            } else {
                if ("3".equals(type)) {
                    result = 10000;
                }
            }
        }
        return result;
    }

}

修改后代码2

public class NotUseComplexConditionTwoAfter {
    public static int getInsurance(String type) {
        if ("1".equals(type)) {
            //死亡
            return 1000000;
        }
        //失业
        if ("2".equals(type)) {
            return 50000;
        }
        if ("3".equals(type)) {
            return 10000;
        }
        return 0;
    }
}

坏味道代码3

public class NotUseComplexConditionThreeBefore {
    public static String eatMethod(Integer type) {
        //苹果吃法
        if (NotUseConsts.FRUITS_APPLE.equals(type)) {
            return "苹果削皮吃";
            //香蕉吃法
        } else if (NotUseConsts.FRUITS_BANANA.equals(type)) {
            return "香蕉剥皮吃";
        }
        return "";
    }
}
class NotUseConsts {
    public static final Integer FRUITS_APPLE = 0;
    public static final Integer FRUITS_BANANA = 1;
}

修改后代码3

public class NotUseComplexConditionThreeAfter {
    public void method(){
        Fruits apple = new Apple("苹果");
        apple.eatMethod();

        Fruits banana = new Banana("香蕉");
        banana.eatMethod();
    }
}

class Banana extends Fruits {
    public Banana(String name) {
        this.name = name;
    }
    @Override
    public void eatMethod() {
        System.out.println(this.name + "剥皮吃");
    }
}

class Apple extends Fruits {
    public Apple(String name) {
        this.name = name;
    }
    @Override
    public void eatMethod() {
        System.out.println(this.name + "削皮吃");
    }
}

abstract class Fruits {
    //水果名称
    protected String name;
    //水果吃法
    public void eatMethod() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

如何深入理解“==”的真正含义

坏味道代码

public class EqualsIntegerBefore {
    public static void method() {
        Integer num1 = 22000;
        Integer num2 = 23000;
        System.out.println(num1 == num2);
    }

}

修改后代码

public class EqualsIntegerAfter {
    public static void method() {
        Integer num1 = 22000;
        Integer num2 = 23000;
        System.out.println(num1.equals(num2));
    }
}

要习惯于用泛型代替原生类型

坏味道代码

public class UseGenericBefore {
    private Object object;

    public UseGenericBefore(Object object) {
        this.object = object;
    }

    public void showType() {
        System.out.println("实际的类型为:" + object.getClass().getName());
    }

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    public static void main(String[] args) {
        UseGenericBefore useGenericBefore = new UseGenericBefore(new Integer(1));
        useGenericBefore.showType();
        int int1 = (Integer) useGenericBefore.getObject();
        System.out.println("value1=" + int1);
        UseGenericBefore useGenericBefore2 = new UseGenericBefore("");
        useGenericBefore.showType();
        String str = (String) useGenericBefore2.getObject();
        System.out.println("value2=" + int1);
        List list = new ArrayList();
        list.add(1);
        list.add("哈哈");
        System.out.println((Integer) list.get(1));
    }

}

修改后代码

public class UseGenericAfter<T> {
    private T object;

    public UseGenericAfter(T object) {
        this.object = object;
    }

    public void showType() {
        System.out.println("实际的类型为:" + object.getClass().getName());
    }

    public T getObject() {
        return object;
    }

    public void setObject(T object) {
        this.object = object;
    }

    public static void main(String[] args) {
        UseGenericAfter<Integer> useGenericBefore = new UseGenericAfter<>(new Integer(1));
        useGenericBefore.showType();
        int int1 = useGenericBefore.getObject();
        System.out.println("value1=" + int1);
        UseGenericAfter<String> useGenericBefore2 = new UseGenericAfter<>("");
        useGenericBefore.showType();
        String str = useGenericBefore2.getObject();
        System.out.println("value2=" + int1);
        List<Integer> list = new ArrayList<>();
        list.add(1);
        System.out.println(list.get(1));
    }

}

如何正确使用通配符的边界

坏味道代码

public class UseWildcardBefore {
    public void method(){
        List<Double> list = new ArrayList<>();
        list.add(1.1);
        read(list);
        List<Integer> list2 = new ArrayList<>();
        list2.add(2);
        read(list2);
    }

    private void read(List<? extends Number> list) {
        for(Object o : list){
            System.out.println(o);
        }
    }

}

修改后代码

public class UseWildcardAfter {
    public void method() {
        List<Number> list = new ArrayList<>();
        write(list);
    }
    private void write(List<? super Number> list) {
        list.add(1.1);
        list.add(2);
        System.out.println(list);
    }

}

如何发挥正则表达式的威力

坏味道代码

public class UseRegularBefore {
    public boolean isMobile(String mobile) {
        if (mobile == null || "".equals(mobile)) {
            return false;
        } else if (mobile.length() != 11) {
            return false;
        } else if (!"1".equals(mobile.substring(0, 1))) {
            return false;
        } else {
            for (int i = 1; i <= 10; i++) {
                char everyNum = mobile.charAt(i);
                if (everyNum < 48 || everyNum > 57) {
                    return false;
                }
            }
        }
        return true;
    }

}

修改后代码

public class UseRegularAfter {
    public boolean validate(String regEx,Object value){
        if(regEx != null && value != null){
            Pattern pattern = Pattern.compile(regEx);
            Matcher matcher = pattern.matcher(value.toString());
            if(!matcher.find()){
                return false;
            }else{
                return true;
            }
        }
        return false;
    }

}

上面示例源码

本文为博主原创文章,未经博主允许不得转载。
更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: