samedi 10 janvier 2015

Should I create a single object for a common method call or use a throw away approach?

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.


Aucun commentaire:

Enregistrer un commentaire