Why scope To minimize local variables?

Hi, this article it said a small detail of Java: Why do you want the scope of local variables is minimized?

Ming did not say dark words ah. Inspiration for this article comes from "Effective Java", the book I had bought a long, long time, the pages have yellowed, bears the traces of time, but I still have not read the book Finish. I am ashamed to say ah.

why? This book always feel a little clumsy translation of Chinese, read boredom boring. Obviously feeling of it very reasonable, but they could not get the slightest interest.

(Finish the sentence, always I felt a little sorry for the book's translator, after all Tucao easily share than done.)

Why say such nonsense, because the fear we feel it is not worth mentioning specifics, the details often determine success or failure ah. It might do a more relaxed state of mind to read. Anyway, I do not like talk of articles, often only after reading a sigh: "quite right ah," but nothing more.

Well, to come to the question.

String [] strs = {"洛阳","牡丹","甲天下"};
List<String> list = Arrays.asList(strs);

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String s = (String) iterator.next();
    System.out.println(s);
}

list.add("沉默王二");
Iterator<String> iterator1 = list.iterator();
while (iterator.hasNext()) {
    String s = (String) iterator1.next();
    System.out.println(s);
}

We use the "naked eye" after reading the above code, will find there a problem?

If you are not careful, it seems really hard to find "copy - paste" caused this problem: condition while the second cycle using a variable before the iterator, instead it should use iterator1 (pasted after missing variables modify). This issue will lead to code at run time throws java.lang.UnsupportedOperationExceptionan error.

To tell the truth, knocking the code of this decade, no less copy and paste, no less because the variables are not pasted completely modified, which led to the emergence of various bug unexpected.

If the scope of a variable is minimized, it really is possible to reduce this because the "copy - paste" and cause errors. For example, the while loop transformed into a for loop.

for (Iterator<String> iterator = list.iterator();iterator.hasNext();) {
    String s = (String) iterator.next();
    System.out.println(s);
}

list.add("沉默王二");
for (Iterator<String> iterator = list.iterator();iterator.hasNext();) {
    String s = (String) iterator.next();
    System.out.println(s);
}

The second for loop code and a for loop identical, even iterator does not need to modify the variable.

On the other hand if, for shorter cycle than the while loop, better readability. There is another for loop most commonly written, the following example.

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

But such an approach is still room for improvement, because from the point of view bytecode, to be called once per cycle size()method.

2: iload_1
3: aload_0
4: getfield      #4                  // Field list:Ljava/util/List;
7: invokeinterface #5,  1            // InterfaceMethod java/util/List.size:()I
12: if_icmpge     40
15: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
18: aload_0
19: getfield      #4                  // Field list:Ljava/util/List;
22: iload_1
23: invokeinterface #7,  2            // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
28: checkcast     #8                  // class java/lang/String
31: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
34: iinc          1, 1
37: goto          2
40: return

size()The method, though brief, but there are also consumed ah. What has consumed it? Said several professional term we feel, for example: create a stack frame, to protect the site when calling the method, the method call is completed to restore the site.

(Allow me to look embarrassed, before writing this article, I have been using this for loop above format seems able to push myself to write articles or progress ah.)

How to improve it, see the following written in this way (highly recommended ah).

for (int i = 0, n = list.size(); i < n; i++) {
    System.out.println(list.get(i));
}

In the loop for two variables declared within the: i and n, n i for holding a limit value, thus reducing the size()number of calls to method (the only one).

Let's look at a piece of code.

String pre_name = "沉默";
String last_name = "王二";

System.out.println(pre_name);
System.out.println(last_name);

The code above looks very neat, no problem, right? It did not abide by the agreement - the scope of local variables is minimized.

scoped variables pre_name ended a little late; scoped variable last_name start a little early. If the first System.out.println()error, then, last_name statement becomes meaningless.

(This is just an example, treatment of variables than likely System.out.println()much more complex.)

The following wording should be good like this.

String pre_name = "沉默";
System.out.println(pre_name);

String last_name = "王二";
System.out.println(last_name);

Some may think this is not splitting hairs it? It really was not, and variable should be the first time when using it in a statement . Otherwise, the scope of a variable or start too early, too late or end.

Well, this article concludes this very brief, but clear "why the scope of local variables you want to minimize."

 

Guess you like

Origin www.cnblogs.com/qing-gee/p/11616726.html