首页 新闻 会员 周边

java中递进式判断如何优化?

0
悬赏园豆:50 [已解决问题] 解决于 2021-06-18 10:36

代码如下,如何优化这类代码?

 private static void test(String a, String b, String c, String d) {
        if (StringUtils.isNotEmpty(a) && StringUtils.isNotEmpty(b) && StringUtils.isNotEmpty(c) && StringUtils.isNotEmpty(d)) {
            //都不为空 do something
        } else if (StringUtils.isNotEmpty(a) && StringUtils.isNotEmpty(b) && StringUtils.isNotEmpty(c) && StringUtils.isEmpty(d)) {
            //abc不为空且d为空 do something
        } else if (StringUtils.isNotEmpty(a) && StringUtils.isNotEmpty(b) && StringUtils.isEmpty(c) && StringUtils.isEmpty(d)) {
            //ab不为空且cd为空 do something
        } else if (StringUtils.isNotEmpty(a) && StringUtils.isEmpty(b) && StringUtils.isEmpty(c) && StringUtils.isEmpty(d)) {
            //a不为空且bcd为空 do something
        } else if (StringUtils.isEmpty(a) && StringUtils.isEmpty(b) && StringUtils.isEmpty(c) && StringUtils.isEmpty(d)) {
            //都为空 do something
        }
    }
AnNong的主页 AnNong | 初学一级 | 园豆:161
提问于:2021-06-16 16:42
< >
分享
最佳答案
1
/**
 * 两种优化方案
 */
public class JudgeOptimize {

    /**
     * 都不为空
     */
    private static final int CODE_CONDITION_ONE = 0000;

    /**
     * abc不为空 d为空
     */
    private static final int CODE_CONDITION_TWO = 0001;

    private static final int CODE_CONDITION_THREE = 0011;

    private static final int CODE_CONDITION_FOUR = 0111;

    private static final int CODE_CONDITION_FIVE = 1111;

    private static void test(String a,String b,String c,String d){
        switch (init(a,b,c,d)){
            case CODE_CONDITION_ONE:
                // DO SOMETHING ...
                break;
            case CODE_CONDITION_TWO:
                //DO SOMETHING ...
                break;
            case CODE_CONDITION_THREE:
                //DO SOMETHING ...
                break;
            case CODE_CONDITION_FOUR:
                //DO SOMETHING ...
                break;
            case CODE_CONDITION_FIVE:
                //DO SOMETHING ...
                break;
        }
    }

    private static int init(String ... allParam){
        if(allParam == null){
            return 1;
        }
        String resultNumberStr = "";
        for (String s : allParam) {
            resultNumberStr += StringUtils.isNotEmpty(s) ? 0 : 1;
        }
        return Integer.valueOf(resultNumberStr);
    }


}

/**
 * 第二种解决方案
 * 全自动 但是涉及反射
 */
@Getter
class SolutionTwo{

    private static Object result;

    @Data
    private static class Action{
        /**
         * 目标类
         */
        private Class targetInvokeClass;

        /**
         * 目标类中目标方法
         */
        private String targetMethodName;

        /**
         * 参数类型
         */
        private Class[] parameterTypes;

        /**
         * 目标方法参数对象
         */
        private Object[] params;

        /**
         * 是否是当前类中方法
         */
        private boolean isCurrentClass;

        /**
         * 是否方法不需要参数
         */
        private boolean isNoParams;

        public Action(){

        }

        public Action(Class targetInvokeClass, String targetMethodName,Class[] parameterTypes, Object[] params, boolean isCurrentClass, boolean isNoParams) {
            this.targetInvokeClass = targetInvokeClass;
            this.targetMethodName = targetMethodName;
            this.parameterTypes = parameterTypes;
            this.params = params;
            this.isCurrentClass = isCurrentClass;
            this.isNoParams = isNoParams;
        }
    }

    /**
     * 映射Map
     * 泛型Object是指令,
     * 泛型Action是指令对应的执行方案
     */
    private static final HashMap<Object,Action> ACTION_MAP = new HashMap<>(16);

    static class ResultAction{

        public void helloWorld(String name){
            System.out.println(name + ",你好世界");
        }

    }


    static {
        //都不为空
        ACTION_MAP.put(0,new Action(ResultAction.class,"helloWorld",new Class[]{String.class},new String[]{"我是张三"},false,false));
        //abc不为空 d为空
        ACTION_MAP.put(1,new Action(ResultAction.class,"helloWorld",new Class[]{String.class},new String[]{"我是李四"},false,false));
        //ab不为空 cd为空
        ACTION_MAP.put(11,new Action(ResultAction.class,"helloWorld",new Class[]{String.class},new String[]{"我是王五"},false,false));
        //a不为空 bcd为空
        ACTION_MAP.put(111,new Action(ResultAction.class,"helloWorld",new Class[]{String.class},new String[]{"我是赵六"},false,false));
        //abcd都为空
        ACTION_MAP.put(1111,new Action(ResultAction.class,"helloWorld",new Class[]{String.class},new String[]{"我是张三他爹"},false,false));
    }

    private static void test(String a,String b,String c,String d){
        int result = init(a, b, c, d);
        Action action = ACTION_MAP.get(result);
        if(action != null){
            handler(action);
        }else{
            System.out.println("未找到对应映射键");
        }
    }

    private static void handler(Action action) {
        try {
            Method method = null;
            Class cls = null;
            if (action.isCurrentClass()) {
                method = getMethod(SolutionTwo.class,action.getTargetMethodName(),action.getParameterTypes());
                cls = SolutionTwo.class;
            }else{
                Class targetClass = action.getTargetInvokeClass();
                method = getMethod(targetClass, action.getTargetMethodName(), action.getParameterTypes());
                cls = action.getTargetInvokeClass();
            }
            result = method.invoke(cls.newInstance(), action.getParams());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
            e.printStackTrace();
        }
    }


    private static Method getMethod(Class cls,String methodName,Class[] parameterTypes) throws NoSuchMethodException {
        return cls.getMethod(methodName,parameterTypes);
    }


    private static int init(String ... allParam){
        if(allParam == null){
            return 1;
        }
        String resultNumberStr = "";
        for (String s : allParam) {
            resultNumberStr += StringUtils.isNotEmpty(s) ? 0 : 1;
        }
        return Integer.valueOf(resultNumberStr);
    }

    public static void main(String[] args) {
        test("1",null,null,null);
    }
}
收获园豆:50
刷最大的碗 | 菜鸟二级 |园豆:279 | 2021-06-18 09:13

第二种方案可行 感谢大佬

AnNong | 园豆:161 (初学一级) | 2021-06-18 10:36
其他回答(2)
0

定义个接口
public interface Invoker {
boolean support(String a, String b, String c);
void invoke(String a, String b, String c);
}
类似于这样去执行
List<Invoker> invokers = new ArrayList<>();
for (Invoker invoker : invokers) {
if (invoker.support(a, b, c)) {
invoker.invoke(a, b, c);
}
}

yytxdy | 园豆:1680 (小虾三级) | 2021-06-16 17:08

这样会产生大量的实现类啊兄弟

支持(0) 反对(0) AnNong | 园豆:161 (初学一级) | 2021-06-16 17:27

@AnNong: 很正常啊,新增类是合理的,一个类作一个事

支持(0) 反对(0) yytxdy | 园豆:1680 (小虾三级) | 2021-06-16 17:29
0

package test;

import java.util.*;

public abstract class Test {
private final Map<Integer, Object> map;

public Test(String... params) {
    map = new HashMap<>(params.length);
    for (int i = 0; i < params.length; i++) {
        map.put(i, params[i]);
    }
}

public abstract void paramsIsNullAndOtherIsNotNullDoSomething();

public abstract void paramsIsNotNullAndOtherIsNullDoSomething();

public abstract void allNotNullDoSomething();

public abstract void AllIsNullDoSomething();

public void paramsIsNullAndOtherIsNotNull(Integer... params) {
    List<Integer> indexList = Arrays.asList(params);
    for (Integer key : map.keySet()) {
        if (indexList.contains(key) && map.get(key) != null) {
            return;
        } else if (!indexList.contains(key) && map.get(key) == null) {
            return;
        }
    }

    paramsIsNullAndOtherIsNotNullDoSomething();
}

public void paramsIsNotNullAndOtherIsNull(Integer... params) {
    List<Integer> indexList = Arrays.asList(params);
    for (Integer key : map.keySet()) {
        if (indexList.contains(key) && map.get(key) == null) {
            return;
        } else if (!indexList.contains(key) && map.get(key) != null) {
            return;
        }
    }

    paramsIsNotNullAndOtherIsNullDoSomething();
}

public void allNotNull() {
    for (Integer key : map.keySet()) {
        if (map.get(key) != null) {
            return;
        }
    }
    allNotNullDoSomething();
}

public void AllIsNull() {
    for (Integer key : map.keySet()) {
        if (map.get(key) == null) {
            return;
        }
    }
    AllIsNullDoSomething();
}


static class DoSomething extends Test {
    public DoSomething(String... params) {
        super(params);
    }

    @Override
    public void paramsIsNullAndOtherIsNotNullDoSomething() {
        System.out.println("参数为空,但其他元素不为空");
    }

    @Override
    public void paramsIsNotNullAndOtherIsNullDoSomething() {
        System.out.println("参数不为空,但其他元素为空");
    }

    @Override
    public void allNotNullDoSomething() {
        System.out.println("所有参数不为空");
    }

    @Override
    public void AllIsNullDoSomething() {
        System.out.println("所有参都为空");
    }
}

public static void main(String[] args) {
    Test test = new DoSomething(null, null, "c", "d");
    test.paramsIsNullAndOtherIsNotNull(0, 1);
    test.paramsIsNotNullAndOtherIsNull(2, 3);
    test.allNotNull();
    test.AllIsNull();
}

}
最后简化成四行代码。。。

dxyoung | 园豆:208 (菜鸟二级) | 2021-06-18 11:19
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册