General Best Practices

This lesson discusses best practices for various aspects of Java Programming

We'll cover the following...

General Best Practices

  1. Strive to minimize the scope of a local variable The best way for minimizing the scope of a local variable is to declare it where it is first used.

    Bad Practice

            // Variable not used immediately but declared
            Random random = new Random(System.currentTimeMillis());
    
            for (int i = 0; i < 10; i++) {
                // ... for body
            }
    
            for (int i = 0; i < 10; i++) {
                // ... for body
            }
    
            // ... more processing
            // .
            // .
            // .
            // ...
    
            if (random.nextBoolean()) {
                // ... if body
            }
    

    Better Practice

            for (int i = 0; i < 10; i++) {
                // ... for body
            }
    
            for (int i = 0; i < 10; i++) {
                // ... for body
            }
    
            // ... more processing
            // .
            // .
            // .
            // ...
           
            // Variable declared closer to where it gets used
            Random random = new Random(System.currentTimeMillis());
            if (random.nextBoolean()) {
                // ... if body
            }
    
    
  2. Initialize every local variable when it is being declared. If you don’t yet have enough information to initialize a variable sensibly, postpone declaring it. One exception to this rule can be a ...