简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM