Reputation: 1796
I have found this question How to generate a random alpha-numeric string? and the answer contains this code:
public final class SessionIdentifierGenerator {
private SecureRandom random = new SecureRandom();
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}
And my question is can I make nextSessionId
static
?
I know that technically I can, but I am curious if it was intentionally made non-static. I know that probably author won't read my question and he won't explain to me what he had is his mind responding to this question, but maybe there is something I don't know and someone can explain me what reasoning could be behind this answer. I think that there is no point in making this method non-static, because I get nothing from creating SessionIdentifierGenerator
object. I'd prefer calling nextSessionId without creating SessionIdentifierGenerator
object.
Upvotes: 2
Views: 795
Reputation: 27575
Yes, technically, you can make the method static
.
The class is final
anyway and doesn't extend
any other class, so the argument of overriding the method wouldn't count here.
As JonK mentioned in comments, the random
field must be made static as well.
Because SecureRandom
is thread-safe, this is not a problem either.
One problem with a static method is that it would be harder to mock from within tests.
Upvotes: 1
Reputation: 5423
Yes, you can make it static
if you want. But why should you?
you may want to read the following then reconsider making things static
:
Upvotes: 1