I'm creating a little rpg fight program just for fun and to practice my java (I'm pretty new hehe).
I have a class called Dice with a method called d20 that rolls a random number between 1 and 20. The method will be used frequently by all other classes in the program.
My question is, should I create a single instance of the Dice class in my main method that can be called by all the other classes too. Does that work? Does it need to be declared as a public reference variable to work? Is this just a poor practice?
Should I be making the method static instead so that I don't need to make an instance of the object at all?
Or should I create the object when the call is to be made and then throw it away afterwards using garbage collection?
I'm not sure the first way even works. The latter two I don't know which is good practice.
My main motivation here is to understand what the best practice is and why.
Best Answer
Have any class that requires a random number source accept a
Function<Integer, Integer>
(or any equivalent functional interface you like) in its constructor.Create a static method
int rollDie(int sides)
that generates a random number from0
tosides
, inclusive. This avoids the redundancy ofrollD20
,rollD8
, etc. Interally this'll probably just be a call toRandom.nextInt(sides + 1)
.You can pass the static method to any class that needs it using a method reference:
For unit testing, you can easily replace
rollDie
with a predictable function:This is equivalent to valenterry's approach but with less boilerplate and possibly more efficient, if the compiler/virtual machine can make use of the fact that the lambda refers to a static method. It's also a bit easier to reuse, since
rollDie
works with any interface containing one method that takes anInteger
and returns anInteger
, so you can use it in other contexts as well.