Java – Single Object vs. Throwaway Approach for Common Method Calls

javaobject-oriented-design

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 from 0 to sides, inclusive. This avoids the redundancy of rollD20, rollD8, etc. Interally this'll probably just be a call to Random.nextInt(sides + 1).

You can pass the static method to any class that needs it using a method reference:

new Character(Dice::rollDie)

For unit testing, you can easily replace rollDie with a predictable function:

new Character(sides -> 5);

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 an Integer and returns an Integer, so you can use it in other contexts as well.

Related Topic