Multiple conditions in an if clause

后端 未结 9 1060
醉梦人生
醉梦人生 2021-02-02 06:44

If I have an if statement that needs to meet these requirements:

if(cave > 0 && training > 0 && mobility > 0 && sleep > 0)
         


        
9条回答
  •  情话喂你
    2021-02-02 07:26

    There is nothing wrong with having multiple, simple conditions in an if statement. However, if it cannot fit into a single line (about 80 characters), you have a few solutions.

    Ultimately, you are not checking whether four variables are greater than zero. You are checking for a set of conditions. The fact that these conditions are (currently) represented by signed integers is not only irrelevant, but is an implementation details that should be hidden away in functions.

    1. Use intermediary flags:

      var valid_location = false;
      if (cave > 0 && training > 0)
          valid_location = true;
      
      var valid_status = false;
      if (mobility > 0 && sleep > 0)
          valid_status = true;
      
      if (valid_location && valid_status)
          // ...
      
    2. Use a function:

      function can_do_this()
      {
          // split conditions into logical groups
      
          // checking location, because you need training if you're
          // in a cave
          if (cave <= 0 || training <= 0)
              return false;
      
          // checking status, because you have to be mobile and
          // sleepy
          if (mobility <= 0 || sleep <= 0)
              return false;
      
          return true;
      }
      
      if (can_do_this())
          // ...
      
    3. Use functions for the individual conditions you need to check:

      function valid_location()
      {
          return (cave > 0 && training > 0);
      }
      
      function valid_status()
      {
          return (mobility > 0 && sleep > 0);
      }
      
      if (valid_location() && valid_status())
          // ...
      

提交回复
热议问题