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

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

    You can use early returns (from a method) to achieve the same effect:

    [Some fixes applied]

      public static boolean areArgsOk(String[] args) {
         if(args == null)
            return false;
    
         if(args.length != 2)
            return false;
    
         if(args[0].equals(args[1]))
            return false;
    
         return true;
      }
    
      public static void main2(String[] args) {
    
            boolean b = areArgsOk(args);
            if(b)
               System.out.println("Args are ok");
      }
    

提交回复
热议问题