Search code examples
dartvariable-declaration

What's the best practice to declare a variable in Dart?


This example is a simple case related to my question.

Case 1: declaring out of the loop

List<List<int>> matrix = [[1,2,3],[4,5,6],[7,8,9]];
List<int> o;
for(int i=0; i<matrix.length; i++) {
    o = List.from(matrix[i]);
    for(int e in o)
        print(e);
}

Case 2: declaring inside the loop

List<List<int>> matrix = [[1,2,3],[4,5,6],[7,8,9]];
for(int i=0; i<matrix.length; i++) {
    List<int> o = List.from(matrix[i]);
    for(int e in o)
        print(e);
}

Does it matter where I declare the variable? Why?


Solution

  • The scope of a local variable should be as small as possible. Thus, declaring a variable inside the loop is a better practice.

    The advantages of doing so:

    • Avoids mixing up of variables having generic names: if a variable is named i and the same variable is referenced in multiple loops, it may get confusing as to what value the variable holds at any part of the program.
    • Compiler issues precise warnings and errors if this local variable gets referenced somewhere else
    • Better optimizations: as the local variable scope is limited to the loop, so no need to store the variable value after the loop is executed. For today's standards, this little optimization doesn't matter much though.
    • Better readability

    Declaring variable inside the loop is good only if you do not need to reuse the updated variable value like:

    int counter = 0;
    for(final i in range(1, 10)) {
        counter++;
        // use variable counter here as a "counter"
    }
    

    In the snippet below, using the variable counter as a counter is invalid as the variable is reinitialized at the start of each loop

    for(final i in range(1, 10)) {
        int counter = 0;
        counter++;
        // use counter here as a "counter"
    }
    

    If you do want to use a variable as a counter(or any other purpose) and update its value inside a loop and use it outside of the scope of the loop then only declare the variable outside of the loop.

    Refrences: