sid-ramakrishnan / ScoreOverFlow

0 stars 0 forks source link

Random objects created and used only once #1

Open Debug1995 opened 5 years ago

Debug1995 commented 5 years ago

Ex: PasswordHashingTest.java[line 29]:

private String generateRandomString(int length) {
    byte[] array = new byte[length];
    new Random().nextBytes(array);
    return new String(array);
}

Spotbugs Explanation: This code creates a java.util.Random object, uses it to generate one random number and then discards the Random object. This produces mediocre quality random numbers and is inefficient. If possible, rewrite the code so that the Random object is created once and saved, and each time a new random number is required to invoke a method on the existing Random object to obtain it.

Our Analysis: In this case, the code creates a random array of bytes in order to generate random passwords to test the password hashing during the login period. The array is then passed as the return value. A new Random object is created each time a new array is created. Thus the Random object is used only once in its entire life cycle. If the test case is run multiple times, this may cause performance concerns as a useless object exists throughout the program. A better way is to create the object only once, save it out the method and invoke its method to generate new random arrays.

TCXX commented 5 years ago

Thank you so much for catching this! Hey @HengruiX @zerocstaker @Zichuan-Wang , can we make it singleton mode?