# Insert Break Statements in For-loops

# Description

Finds the Enhanced For-loops whose sole purpose is to compute a boolean value without causing side effects and inserts a break statement immediately after the boolean value is computed. Thus, eliminating redundant loop iterations.

# Benefits

Improves performance by eliminating redundant cycles in Enhanced For-loops.

# Tags

# Code Changes

# Searching for a fixed value

Pre

    boolean found = false;
    for(String value : values) {
        if(value.equals("John")) {
            found = true;
        }
    }

Post

		boolean found = false;
		for(String value : values) {
			if(value.equals("John")) {
				found = true;
                break;
			}
		}

# Matching a value in another Collection

Pre

    boolean found = false;
    for(String value : values) {
        if(collection.contains(value)) {
            found = true;
        }
    }

Post

    boolean found = false;
    for(String value : values) {
        if(collection.contains(value)) {
            found = true;
            break;
        }
    }

# Wrapping body into a code block

Pre

    boolean empty = false;
    for(String value : values)
        if(value.isEmpty()) 
            empty = true;

Post

    boolean empty = false;
    for(String value : values)
        if(value.isEmpty()) {
            empty = true;
            break;
        }

# Limitations

This rule cannot be applied if the method invocations occurring in the if condition might cause side effects in the program execution.

Pre

    boolean found = false;
    for(String value : values) {
        if(consumeValue(value)) {
            found = true;
        }
    }

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

Property Value
Rule ID InsertBreakStatementInLoops
First seen in jSparrow version 3.9.0
Minimum Java version 5
Remediation cost 2 min