Effective java study notes Chapter VIII (1)

2010-05-13  来源:本站原创  分类:Java  人气:190 

To minimize the scope of local variables

Older programming languages (such as the C language) requires a code of local variables must be declared at the beginning of the block, out of habit, some programmers have inherited this "good practices", the habit should be corrected. Again, Java allows you to place any statement can appear variable declaration.

If the scope of local variables to minimize the most effective way is to use it in the first place a statement. If the variable declaration before use, it will only cause confusion ----- For readers trying to understand the program functions, this gives another will distract attention from the factors. Wait until the variable is used when the reader has probably can not remember the variable type or initial value of.

Premature declaration of local variables will not extend its scope too early, but the end was too late. The scope of local variables to be declared from its point began to expand until the end of a fast outside. If the variable is in the "block to use it" beyond the statement, when the program exits after the block, the variable is still visible. If the variable is used in its target area before or after accidental use, the consequences are disastrous.

Almost every local variable declaration should include an initialization expression. If you do not have enough meaningful information to initialize a variable, this statement should be postponed until the date can be initialized. There is an exception to this rule the case with try-catch related. If a variable is a method of initialization, and this method may throw an exception under check (checked exception), the variables to be initialized within try block. If the variable value must be outside the try block is used to, must be declared before the try block, but before the try block, it can not be "meaningful initialization."

A simple example

public  Connection getConnection(){
                Connection conn=null;
            try {
                } catch (SQLException e) {
                return conn;

Cycle provides a unique opportunity to minimize the scope of the variable. Whether traditional or for-each form of, for loop statement cycle variables are allowed, it's scope is limited to just within the range of needs. This includes the loop body, and the cycle before the initialization, test, update the part. Therefore, if the loop is no longer required after the termination of the contents of the variable loop, for loop while loop on the priority.

For example, the following is a set of preferred practices traverse

for(Element e:c){

Before release in java1.5, the preferred approach is as follows

for(Iterable i=c.iterable();i.hasNext()){

In order to understand why this for loop better than the while loop, please consider the following code fragment, which contains two while loop, and a BUG;

Iterator<Element> i=c.iterator();
                Iterator<Element> i2=c2.iterator();

The second loop includes a "cut and paste --- paste" error: it is supposed to initialize a new variable i2, but using the old loop variable i, unfortunately, when i was still within range. Result code still compile and run time does not throw an exception, but doing it really wrong. Because this error is occurring quietly, it may not appear in a long time was found.

If similar "cut and paste --- paste" error occurred in the previous cycle of exchange of any kind for the result code can not compile. Before the start of the second cycle, the first element of the loop variable has not within its scope a.

for(Iterable<Element> i=c.iterable();i.hasNext()){
                // Compile error prompt variable not found  i
                for(Iterable<Element> i2=c2.iterable();i.hasNext()){

Also, if you are using for loop, guilty of this "cut and paste --- paste" the possibility of error would be greatly reduced, because usually there is no need to declare two different loop variable name. Cycle is completely independent, so do not reuse the name of the variable element of any hazards. In fact, this is a very popular practice.

Use for loop as compared with the use of while loop there is another advantage: shorter, thus increasing the readability.

Here is another of the scope of local variables to minimize the cycle approach.

for(int i=0;i=sss();i<n;i++){

On this point of concern is that it has two loop variables: i and n, the two have exactly the same scope. The second variable n is used to save the first variable limits, in order to avoid redundancy in the calculation of each iteration the cost of implementation. Typically, if the loop involved in the method call, it can ensure that each iteration will return the same result.

The latter "will minimize the scope of local variables" approach is to approach small and concentrated. If the two operations into a single method, and one of the local variables related to the operation is likely to occur in the implementation of other operations within the scope of code. To prevent this from happening, so long as this is divided into two, the implementation of an action for each method.

  • Effective java study notes Chapter VIII (1) 2010-05-13

    To minimize the scope of local variables Older programming languages (such as the C language) requires a code of local variables must be declared at the beginning of the block, out of habit, some programmers have inherited this "good practices",

  • effective java Study Notes - 3 2010-07-28

    Article VII: rewrite as much as possible to comply with the agreement equals 7.1 During comparison, the comparison does not require null values can be directly used for the null instanceof return false directly 7.2 Comparison of the domain will affec

  • Effective java study notes 2010-08-01

    1. Static factory method instead of constructor Such as: public static Boolean valueOf (boolean) ( return (b? Boolean.TRUE: Boolean.FALSE); ) A class provides a static factory method is good a. easy to read, the return type explicitly b. call does no

  • Effective Java study notes section 4 --- avoid creating duplicate objects 2011-04-20

    If an object is a non-variable, then it can be reused on the program, such as: / / Not recommended, "test" has always been a String instance, if this method is frequently a loop or a call, it will seriously affect performance String s = new Stri

  • effective java Study Notes - 4 2010-07-28

    8.3 Method implementation tips 1. To a non-0 constant, such as 17. Save results in a more variable 2. The object of each domain to do some action calculating the hash code c 2.1 boolean ---> c = f? 0:1 2.2 byte char short int -> (int) f; 2.3 long ty

  • Effective Java study notes --- section 2 of the trial to strengthen singleton property private constructor 2011-04-20

    There are two ways to achieve singleton: Method one: public static final field is a member, member's statement is very clear expression of this class is a singleton. view plaincopy to clipboardprint? public class Elvis { public static final Elvis INS

  • Effective Java study notes --- Article 3 by private constructors can not be instantiated to strengthen the capacity of 2011-04-20

    In object-oriented programming, if there are too many static properties and static methods only class; so, object-oriented thinking may be wiped out in this. However, not object-oriented program that should not appear only static properties and stati

  • Effective Java study notes --- Article 5 of the object to eliminate outdated references 2011-04-20

    Garbage collector will not be on the "reference date" (will never be lifted in a reference to) the object of a recall. Such as: the first element of the array to increase further reduce it, the subscript is greater than size () is the date that

  • Effective Java study notes to avoid the use of Article 6 of the end of the function --- 2011-04-20

    End of the function (finalizer) can be used to recover the object can not be reached, that is the end of the life cycle of the object, the end of the function can be used to recover the resources allocated for the object. However, the end of the func

  • Effective Java study notes carefully Article 10 rewrite clone --- 2011-04-21

    To be an object Clone, then to achieve the Clone () interface, this interface does not define any way, but if you do not implement this interface, then call the clone method, when there will be CloneNotSupportedException, this is the type of interfac

  • Effective Java 2 study notes Chapter 5 Generic 2009-01-15

    Article 23-29 of that chapter, focuses on the use of generic programming to the safety benefits as well as the API can be more widely used. 23: Do not use the original code in the new ecological types Using the original eco-types, such as list, you c

  • Spring in Action Study Notes - Chapter IV conquest database (change) 2008-09-28

    Spring2.0 official version (http://www.springframework.org/download) Spring2.0 Chinese documents (http://spring.jactiongroup.net/viewtopic.php?t=2279&sid=0906ae6a913537b249e501db5b54c181). In the previous study, we have learned the core Spring framew

  • 10 struts2 java study notes 2010-10-28

    Recently I have spare time Java Virtual Machine Research, the intern assigned to the project team inside, do not want it used to be free, and managed to find time to continue the topic post. I intend to end some of J2ee and then talk about the JVM an

  • sed and awk rookie notes - Chapter VIII of the conditions, loops and arrays 2011-01-08

    Chapter VIII of the conditions, loops and arrays awk and loop structure in the conditions is to learn the c language. Conditional statement if (expression) action1 [Else action2] if (x) print x # x is a non-0 value of the test if (x == y) print x # t

  • thinking in java study notes (a) 2011-08-20

    Introduction: ready to once again take a look at this classic book, read it twice before, and now think, that the result is not particularly good, so we prepared to look at the third time EDITORIAL words: The author made a few points inside - java it

  • Effective Java 2 study notes chapter 7 method 2010-03-30

    Article 38: Check the validity of arguments When you write a method or constructor, it should consider what limits its argument. These restrictions should be written documents, and the beginning of each method, by showing the check to the implementat

  • design patterns java study notes 2010-05-10

    Today take some time to learn the system under design mode, from the Internet to find a point of information and the learning experience of predecessors, 1: Learning goals and methods of design patterns (master's recommendation summary references) De

  • thinking in java study notes (b) 2011-08-20

    Chapter <br /> Shenma main types, but also difficult listening, I go to Le, called basic types do not you? Where the existence of this object, or the jvm which is more realistic, here about the stack, non-constant static ram even register that the c

  • Java Study Notes (1) - Object-Oriented 2009-01-03

    Next from the Internet, a Java video courseware, the following content is based on what they hear and do the course notes. 1, object-oriented - is a kind of thinking, a problem-solving model. In other words, whether we encounter any problems, all nee

  • <Linux Kernel Development> Study Notes Chapter 2010-04-16

    Linux kernel has been very interested in long to be in-depth study, because of their present level of more food, so recorded in the blog to learn the ideas and experiences, a record myself, but also can supervise their own the learning process; secon