Item 57: Minimize the scope of local variables

Declare the variable where it is first used
The reader will not be distracted to figure out where the variable is declared

Prefer for loops to while loops, assuming the contents of the loop variable aren’t needed after the loop terminates.

Advantages of for lops over while loops

  • Eliminate copy-paste errors
  • Shorter and more readable
  • Declare loop variables, limiting their scope to the exact region where they’re needed.
		List<Integer> list = new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		list.add(3);

		// Not a best practice! Variable "i" might be used somewhere later, such
		// as the for-loop below
		Iterator<Integer> i = list.iterator();
		while (i.hasNext()) {
			Integer value = i.next();
			System.out.println(value);
		}

		// Idiom for iterating when you need the iterator but the the best. Look
		// at the Item 58 for better approach!
		for (Iterator<Integer> j = list.iterator(); j.hasNext();) {
			Integer value = j.next();
			System.out.println(value);
		}

		// ...Then you wrote a 100 lines of code here and forgot the Iterator
		// variable "i"...

		// What happens if you accidentally use the variable "i" below? :)
		for (Iterator<Integer> j = list.iterator(); j.hasNext();) {
			Integer value = i.next(); // ???
			System.out.println(value);
		}

Leave a Reply

Your email address will not be published. Required fields are marked *