How to split up complex conditions and keep short circuit evaluation?

前端 未结 11 1901
清歌不尽
清歌不尽 2020-12-17 16:55

Sometimes conditions can become quite complex, so for readability I usually split them up and give each component a meaningful name. This defeats short-circuit evaluation ho

11条回答
  •  庸人自扰
    2020-12-17 17:43

    This question is from 2009 but in the future (Java 8) we will be able to use Lambda expressions that may be for this context just like boolean expressions but you can use it so they are only evaluated when needed.

    public static void main2(String[] args) {
    
        Callable argsNotNull = () -> args != null;
        Callable argsLengthOk = () -> args.length == 2;
        Callable argsAreNotEqual = () -> !args[0].equals(args[1]);
    
        if (argsNotNull.call() && argsLengthOk.call() && argsAreNotEqual.call()) {
            System.out.println("Args are ok");
        }
    }
    

    You can do the same with java 5/6 but it is less efficient and much more ulgy to write with anonymous classes.

提交回复
热议问题