Should I instantiate instance variables on declaration or in the constructor?

前端 未结 15 1865

Is there any advantage for either approach?

Example 1:

class A {
    B b = new B();
}

Example 2:

class A {
    B b;         


        
15条回答
  •  终归单人心
    2020-11-22 06:52

    my personal "rule" (hardly ever broken) is to:

    • declare all variables at the start of a block
    • make all variables final unless they cannot be
    • declare one variable per line
    • never initialize a variable where declared
    • only initialize something in a constructor when it needs data from the constructor to do the initialization

    So I would have code like:

    public class X
    {
        public static final int USED_AS_A_CASE_LABEL = 1; // only exception - the compiler makes me
        private static final int A;
        private final int b;
        private int c;
    
        static 
        { 
            A = 42; 
        }
    
        {
            b = 7;
        }
    
        public X(final int val)
        {
            c = val;
        }
    
        public void foo(final boolean f)
        {
            final int d;
            final int e;
    
            d = 7;
    
            // I will eat my own eyes before using ?: - personal taste.
            if(f)
            {
                e = 1;
            }
            else
            {
                e = 2;
            }
        }
    }
    

    This way I am always 100% certain where to look for variables declarations (at the start of a block), and their assignments (as soon as it makes sense after the declaration). This winds up potentially being more efficient as well since you never initialize a variable with a value that is not used (for example declare and init vars and then throw an exception before half of those vars needed to have a value). You also do not wind up doing pointless initialization (like int i = 0; and then later on, before "i" is used, do i = 5;.

    I value consistency very much, so following this "rule" is something I do all the time, and it makes it much easier to work with the code since you don't have to hunt around to find things.

    Your mileage may vary.

提交回复
热议问题