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

前端 未结 11 1815
清歌不尽
清歌不尽 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:38

    Split it out into a separate function (to improve readability in main()) and add a comment (so people understand what you are trying to accomplish)

    public static void main(String[] args) {
        if (argumentsAreValid(args)) {
                System.out.println("Args are ok");
        }
    }
    
    
    public static boolean argumentsAreValid(String[] args) {
        // Must have 2 arguments (and the second can't be the same as the first)
        return args == null || args.length == 2 || !args[0].equals(args[1]);
    }
    

    ETA: I also like Itay's idea of using early returns in the ArgumentsAreValid function to improve the readability.

提交回复
热议问题