# Reuse Random Objects

# Description

Creating a new Random() object each time a random value is needed is inefficient and may produce numbers which are not random. This rule extracts reusable java.util.Random (opens new window) objects, from local variables to class or instance fields. Note that SonarCloud classifies this rule as a Critical Bug, S2119 (opens new window).

# Benefits

Improves the unpredictability and efficiency of the generated random values.

# Tags

# Code Changes

# Extracting an Instance Field

Pre

public void sampleMethod(String value) {
    Random random = new Random();
    int nextIndex = random.nextInt();
    //...
}

Post

private Random random = new Random();

public void sampleMethod(String value) {
    int nextIndex = random.nextInt();
    //...
}

# Extracting a Class Field

Pre

public static void sampleMethod(String value) {
    Random random = new Random();
    int nextIndex = random.nextInt();
    //...
}

Post

private static Random random = new Random();

public static void sampleMethod(String value) {
    int nextIndex = random.nextInt();
    //...
}

# Reusing an Existing Field

Pre

private Random random = new Random();

public void sampleMethod(String value) {
    Random random = new Random();
    int nextIndex = random.nextInt();
    //...
}

Post

private Random random = new Random();

public void sampleMethod(String value) {
    int nextIndex = random.nextInt();
    //...
}

# Using Secure Random Initializer

Pre

public void sampleMethod(String value) {
    Random random = new SecureRandom();
    int nextIndex = random.nextInt();
    //...
}

Post

private Random random = new SecureRandom();

public void sampleMethod(String value) {
    int nextIndex = random.nextInt();
    //...
}

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 ReuseRandomObjects
First seen in jSparrow version 3.20.0
Minimum Java version 1.1
Remediation cost 5 min
Links