87. LVTI and variable scope

The clean code best practices include keeping a small scope for all local variables. This is one of the clean code golden rules that was followed even before the existence of LVTI.

This rule sustains the readability and debugging phase. It can speed up the process of finding bugs and writing fixes. Consider the following example that breaks down this rule:

// Avoid
...
var stack = new Stack<String>();
stack.push("John");
stack.push("Martin");
stack.push("Anghel");
stack.push("Christian");

// 50 lines of code that doesn't use stack

// John, Martin, Anghel, Christian
stack.forEach(...);

So, the preceding code declares a stack with four names, contains 50 lines of code that don't use this stack, and finishes with a loop of this stack via the forEach() method. This method is inherited from java.util.Vector and will loop the stack as any vector (John, Martin, Anghel, Christian). This is the order of traversal that we want.

But later on, we decide to switch from the stack to ArrayDeque (the reason is irrelevant). This time, the forEach() method will be the one provided by the ArrayDeque class. The behavior of this method is different from Vector.forEach(), meaning that the loop will traverse the entries following the Last In First Out (LIFO) traversal (Christian, Anghel, Martin, John):

// Avoid
...
var stack = new ArrayDeque<String>();
stack.push("John");
stack.push("Martin");
stack.push("Anghel");
stack.push("Christian");

// 50 lines of code that doesn't use stack

// Christian, Anghel, Martin, John
stack.forEach(...);

This was not our intention! We switched to ArrayDeque for other purposes, not for affecting the looping order. But it is pretty difficult to see that there was a bug in the code since the part of the code containing the forEach() part is not in proximity of the code where we completed the modifications (50 lines below this line of code). It is our duty to come up with a solution that maximizes the chances of getting this bug fixed quickly and avoiding a bunch of scrolling up and down to understand what is going on. The solution consists of following the clean code rule we invoked earlier and writing this code with a small scope for the stack variable:

// Prefer
...
var stack = new Stack<String>();
stack.push("John");
stack.push("Martin");
stack.push("Anghel");
stack.push("Christian");

// John, Martin, Anghel, Christian
stack.forEach(...);

// 50 lines of code that doesn't use stack

Now, when we switch from Stack to ArrayQueue, we should notice the bug faster and be able to fix it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.33.235