LilasCorner / jlootbox

Other
1 stars 0 forks source link

Enums in Java #4

Open JohnTMurphy-NIU opened 2 years ago

JohnTMurphy-NIU commented 2 years ago

Consider switching the three public static final int variables 'ALWAYS_BUY', 'COIN_FLIP', and 'PRICE' in the Player class (lines 22-24) to a Java enum, probably a nested inner class of Player, so:

public class Player{

public static enum DecisionStrategy{
   ALWAYS_BUY,
   COIN_FLIP,
   PRICE
}

... (rest of Player class...)

This effectively creates a new class type Player.DecisionStrategy with three values. A lot of the code will stay exactly as it is, but instead of 'int' variables (like 'decisionStrat' on line 27) you will use Player.DecisionStrategy (or inside Player, just 'DecisionStrategy') as the data type. You can optionally make this a stand-alone enum instead of an inner class of Player; it depends on what seems most intuitive to you. (I like the inner class, but YMMV).

This kind of change doesn't affect the way the code runs, and it possibly doesn't affect the efficiency of the code at run time, but it may make the code more easily manageable and legible, which saves time when you want to add a new kind of decision strategy. You don't have to think about what new integer value to assign; that gets baked into the enum- you don't know which one is '0', which one is '1', etc., and as long as you are only comparing equality (or using in switch/case statements) this doesn't matter. If you want to extend so that there are subcategories (suppose, for example you had 7 options and sometimes you needed the first four vs. the last three...), you can actually do that more easily in an enum, too. Enum members also have a 'name()' attribute that can be used to move from enum to String, which can be helpful when printing, and there is even a route to go from String to enum, and avoid the switch-style at line 62 by replacing it with:

decisionStrat = Enum.valueOf(Player.DecisionStrategy.class, strat); 

Again, this doesn't change functionality, but it can simplify the code.