DEV Community

Ross Holloway
Ross Holloway

Posted on • Updated on

Improving a snippet of code

While working on an Open Source project, I came across this piece of code:

public void clear() {
        Object[] items = this.items;
        for (int i = 0, n = size; i < n; i++)
            items[i] = null;
        size = 0;
    }
Enter fullscreen mode Exit fullscreen mode

I thought this was a great opportunity to share how it might be improved.

Notes:

  • Size is a field declared in the class.
  • For simplicity, I have replaced T[] with Object[] in this article. This is a parameterized class in the source code.

1. Braces around the loop

Although Java will happily compile the code, braces should wrap the for loop:

public void clear() {
        Object[] items = this.items;
        for (int i = 0, n = size; i < n; i++) {
            items[i] = null;
        }
        size = 0;
    }
Enter fullscreen mode Exit fullscreen mode

This clarifies that size = 0; is not contained within the loop.

2. A redundant local variable

The class declares a field called items, which is an Array of Objects. This method starts by assigning that Array to a local variable, also named items, which is then used in the loop.
However, there is no reason that this field cannot be referenced from within the loop, therefore making the local variable redundant:

public void clear() {
        //Object[] items = this.items;
        for (int i = 0, n = size; i < n; i++)
            this.items[i] = null;
        size = 0;
    }
Enter fullscreen mode Exit fullscreen mode

3. Another redundant variable, within the loop

In this style of for loop in Java, 3 things are defined in the parentheses - a variable or variables to be used within the loop (usually i), a condition for determining if the loop should continue, and finally how the loop should progress.

In this particular code, a local variable n is declared and assigned to the size field. This is then used in the end condition - the loop shall only execute while i is less than n.

Cutting out the middle man, this is effectively saying that the loop shall only execute while i is less than size, and so, we can simplify the code:

public void clear() {
        Object[] items = this.items;
        for (int i = 0; i < size; i++)
            items[i] = null;
        size = 0;
    }
Enter fullscreen mode Exit fullscreen mode

Bringing the changes together

To recap, we started with this block of code:

public void clear() {
        Object[] items = this.items;
        for (int i = 0, n = size; i < n; i++)
            items[i] = null;
        size = 0;
    }
Enter fullscreen mode Exit fullscreen mode

After our changes, this is simplified and clarified to:

public void clear() {
        for (int i = 0; i < size; i++) {
            items[i] = null;
        }
        size = 0;
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)