ctomek
ctomek

Reputation: 1796

Static token generation?

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

Answers (2)

Alex Shesterov
Alex Shesterov

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

nafas
nafas

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:

  1. Why are static variables considered evil?
  2. https://www.quora.com/What-are-the-advantages-and-disadvantages-of-having-a-static-method-in-Java
  3. http://devsolvd.com/questions/java-when-to-use-static-methods

Upvotes: 1

Related Questions