0

I read that invoking instance methods on static variables/methods is considered bad practice( I don't know exactly why but that's not the question anyway).

Eg:

class Dice
{
    private int value;
    private static Random randomizer=new Random(); 
    
    public int setAndget_DiceValue()
    {
        value=randomizer.nextInt(6)+1; //Accessing static variable via instance class. Any alternatives?
        return value;
    }
}

What are then alternatives to modifying a static variable that doesn't involve invoking instance method? Even if I used a static method on randomizer, I would then have to use that instance method on a static method which is still considered bad practice.

Edit: Some places I first saw about this being considered a bad practice:

1 ) Writing to a static variable in an instance method, why is this a bad practice?

2 ) A comment to the OP's post: Can non-static methods modify static variables. He was a high-rep user so I was inclined to believe him.

3 )enter image description here

Andreas
  • 154,647
  • 11
  • 152
  • 247
HelloWorld
  • 193
  • 2
  • 8
  • 3
    Where have you read that it's bad practice? It's not. You have either misunderstood it, or taken it out of context. – Sweeper Jun 28 '20 at 01:40
  • share the link in where you got this information – beastlyCoder Jun 28 '20 at 01:41
  • Nothing wrong with that code, but if your program is multithreaded, you should heed this note in the javadoc of [`Random`](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html): *Instances of `java.util.Random` are threadsafe. However, the concurrent use of the same `java.util.Random` instance across threads may encounter contention and consequent poor performance. Consider instead using [`ThreadLocalRandom`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadLocalRandom.html) in multithreaded designs.* – Andreas Jun 28 '20 at 01:44
  • @Andreas, sorry I'm a beginner and haven't reached multithreading yet – HelloWorld Jun 28 '20 at 01:47
  • 1
    1) Not applicable, since you are not writing to the static variable. 2) Not applicable, since you are not modifying the static variable. 3) Not applicable, since you are not returning the value of the static variable. – Andreas Jun 28 '20 at 01:47
  • @Andreas, makes sense now! I made a dumb mistake again – HelloWorld Jun 28 '20 at 01:50

1 Answers1

0

Usually the static variables will be accompanied by, final so once initialized they cannot be reassigned with a different value inside the class.

The only invalid context would a static method trying to use a instance level variable or a method directly but I don't think the converse is invalid.