# 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();
//...
}
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.