天天看點

将局部變量的作用域最小化

    使一個局部變量的作用域最小化,最有力的技術是在第一次使用它的地方聲明。避免在使用前很早就聲明一個局部變量,這樣擴大範圍,造成誤用。

    幾乎每一個局部變量在聲明的時候都應該包含一個初始化表達式。但有時這對try-catch不容易做到,如果try裡面才要使用這個變量,而try-catch後,還要繼續使用這個變量,那麼隻能講這個變量聲明在try-catch之前,并且沒有合适的初始化。

    使用for循環比while容易避免變量的範圍變大,後面誤用。比如:

Iterator i = c.iterator();
                while (i.hasNext()){
                    doSomething(i.next());
                }

                Iterator i2 = c2.iterator();
                while (i.hasNext()){
                    doSomething(i2.next());
                }
           

     這樣i都誤用,導緻無法周遊c2.

for(Iterator i = c.iterator(); i.hasNext(); ){
            doSomething(i.next());
        }
        
        //  Compile-time error - the symbol i cannot be resolved
        for(Iterator i2 = c2.iterator(); i.hasNext();){
            
        }
           

      利用for循環,可以将i 作用域限定在循環中,避免了誤用