I'm working (a bit) on a (turn-based strategy) game. There are two classes relevant for the question:
State
: This is an immutable class, which exposes all its fields (either via getters or another way, as I felt appropriate). The state is a bit complicated, so I decomposed it into several classes in the package...state
Command
: This is an abstract immutable class with a couple of subclasses likeMoveCommand(Field from, Field to)
,PassCommand()
,BidCommand(int amount)
, etc. in the package...command
. All of fields have public getters.
I need one of the two methods
State Command.applyTo(State)
orState State.apply(Command)
returning the new state (obtained by applying the command to the state).
Using the first method looks better at the first sight, since it dispatches to different implementations of applyTo
in the subclasses of Command
. Unfortunately, it forces me to fiddle with the many details of State
in the class Command
. In order to make it work, I need something like MutableState
, or State.Builder
, or a many-args constructor of State
, or whatever.
Using the second method looks ugly, as it'd force me to use instanceof
(or some other ugly way to simulate the virtual method dispatch). OTOH, it would concentrate the working with State
in the class itself.
So I think the first method is the way to go. With Command
and State
each in its own package it means that MutableState
(or whatever gets used for building the resulting State
) need to be a public class since there are no friend
s in Java. No real problem, but not nice, is it?
So what is the proper design?