hoping for your help! I'm doing a java project that reproduces the logo language and im capped as I can't find an elegant and not too complicated way to switch between different rules / instructions, the project focuses on advanced programming and the use of Stream () is suggested; Predicate (); Function (); BiFunction () ect etc this is the list of instructions that I have implemented but that I have no idea how to branch them, i take them as a String:
- FORWARD (int);
- BACKWARD (int);
- LEFT (int);
- RIGHT (int);
- CLEARSCREEN;
- HOME;
- PENUP;
- PENDOWN;
- SETPENCOLOR (int) (int) (int);
- SETFILLCOLOR (int) (int) (int);
- SETSCREENCOLOR (int) (int) (int);
- SETPENSIZE (int);
- RIPETI (int) [ (cmds) ];
- Repeats the sequence of commands in the command list (cmds)
I have thought of an if () else () or a switch () but it does not seem very elegant
CodePudding user response:
If a switch would work but you don't want the method to have too many lines, you could try using a map, either from String to method calls (for which you could use lambdas), or from Enum values to the same.
Map<String, Runnable> operations = Map.ofEntries(
Map.entry("FORWARD", () -> action.forward()),
Map.entry("BACKWARD", () -> action.backward(),
// . . .
);
Or
Map<Instruction, Runnable> operations = Map.ofEntries(
Map.entry(Instruction.FORWARD, action::forward),
Map.entry(Instruction.BACKWARD, action::backward),
// . . .
);
Note that in the second example I used method references for the calls to the Action object, which I'm assuming you have an instance of at this point.
The problem is, your instructions take different numbers of parameters, so that is really just a sketch of a solution. You'll have to figure out how to apply it to your use case. In particular, you haven't mentioned how the Action methods accept the parameters. I suppose each one takes 0, 1, or multiple parameters, depending on the instruction.
One thing you could do is parse each command into an Enum instance for that command, and any parameters into a separate object; maybe a List<Integer>
. I don't know if you can modify the Action class to accept that list instead of the individual parameters. Or maybe modify it to take e.g. forward(int... params)
and you could then pass an int[]
of the parameters.
Hopefully this will at least give you some ideas that will get you unstuck.