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

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

    Your first solution is good for this kind of complexity. If the conditions were more complex, I would write private methods for each check you need to run. Something like:

    public class DemoStackOverflow {
    
        public static void main(String[] args) {
        if ( areValid(args) ) {
            System.out.println("Arguments OK");
        }
        }
    
        /**
         * Validation of parameters.
         * 
         * @param args an array with the parameters to validate.
         * @return true if the arguments are not null, the quantity of arguments match 
         * the expected quantity and the first and second are not equal; 
         *         false, otherwise.
         */
        private static boolean areValid(String[] args) {
           return notNull(args) && lengthOK(args) && areDifferent(args);
        }
    
        private static boolean notNull(String[] args) {
           return args != null;
        }
    
        private static boolean lengthOK(String[] args) {
           return args.length == EXPECTED_ARGS;
        }
    
        private static boolean areDifferent(String[] args) {
           return !args[0].equals(args[1]);
        }
    
        /** Quantity of expected arguments */
        private static final int EXPECTED_ARGS = 2;
    
    }
    

提交回复
热议问题