I need to model a very simple mobile object (Robot
) on a rectangular grid. Its state is described by position
(basically a pair of integers) and direction
(e.g., N, E, S, W). It only has two methods (apart from constructor): it can move one step in its direction
, or rotate by 90, 180 or 270 degrees.
Apart from the obvious performance issues and any language-specific considerations, what factors should I consider when deciding whether to make Robot
instances mutable (methods modify state) or immutable (methods return a newly created robot with the new state)? Instances of this class will be used in various simulations (I intentionally omit the details to get a clearer understanding of overall principles).
(Edited to clarify) When I think of a robot, the natural picture in my mind is a movable thing, which would correspond to a mutable object. That said, it's not hard for me to overcome this mental association and think of robots as little marks on the grid that are created (and destroyed if no other reference points to them) every time they move. So I would not worry about what feels natural, and would just choose what works better code-wise.
I was planning to model position
and direction
as attributes of robot
. Regardless of whether robot
itself is immutable, I was planning to make the types of position
and direction
objects immutable just because it's more natural for me to think of them as such (e.g., when I talk about a "point on a grid", I imagine it remains in the same place forever; same for a "direction").
Robot
objects? If they mutate the object, should other objects referencing that object notice the changed state? Maybe you should have both a mutable and immutable version (mutable could derive from immutable, same behaviors just without mutable ones), exposing the mutable type only where the object should be mutated. – Dioxin Nov 13 '16 at 17:57