简体   繁体   English

应该在哪里声明变量?

[英]Where should variables be declared?

I have a complicated condition inside else block inside a loop. 我在循环内的else块中有一个复杂的条件。 So I decided to form some new variables to simplify this condition. 因此,我决定形成一些新变量来简化这种情况。 Where should I declare these variables? 我应该在哪里声明这些变量?

//here 1
for (...) {
   //here 2
   if(...) {

   } else {
      //here 3
      if (cond1 && cond2){}
   }
} 

You should declare variables closest as possible to their usages, and in the "smallest" scope possible. 您应该声明尽可能接近其用法的变量,并且应在“最小”范围内。

In your example, if cond1,cond2 are used ONLY when you write them in the sample, they should be declared in here 3 . 在您的示例中,如果仅在将它们写入示例中时使用cond1,cond2,则应在here 3声明它们。

您应该在需要的地方声明变量,因此在这种情况下,可能在here 3

Probably the best solution is this : 最好的解决方案可能是这样的:

 boolean cond1,cond2 = false;
    for (...) {
       //here 2
       if(...) {

       } else {
          cond1 = ...
          cond2 = ...
          if (cond1 && cond2){}
       }
    } 

this allows you to allocate no memory for variables at each iteration. 这使您在每次迭代时都不会为变量分配内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM