# Reuse Random Objects

# Properties

Property Value
Rule ID ReuseRandomObjects
First seen in jSparrow version 3.20.0
Minimum Java version 1.1
Remediation cost 5 min
Links S2119

# 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 objects, from local variables to class or instance fields. Note that SonarCloud classifies this rule as a Critical Bug, S2119.

# Benefits

Improves the unpredictability and efficiency of the generated random values.

# 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();
    //...
}

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊