I have a class Robot
, which should contain method Move(...)
.
Robot
is an instance class, you can have more robots working. I thought about making Move
static method, because all robots use same logic when moving somewhere.
Robots contains information about their position, therefore I need to pass instance of Robot
to Move
method. There is also parameter Direction
, which is enum (West, East, ...).
What is better and why?
public static Move(ref Robot rob, Direction dir)
{
rob.Position = ...
}
or
public Move(Direction dir)
{
this.Positon = ...
}
Is there any performance or memory difference?
You describe exactly all the reasons why move()
should be an instance method. It needs access to the fields, and instance methods implicitly have the object reference as 'this'.
You didn't specifically ask about the language you want to do this in, but in Java there is no penalty on memory for either and performance should be so close that it might be the same. For other languages, I suspect the same is true.
Memory and performance should be identical.
However, think how your code will read. Moving several robots:
foreach(Robot robot in robots) {
robot.Move("left");
}
is much cleaner than:
foreach(Robot robot in robots) {
Robot.Move(robot,"left");
}
Also, even if you aren't accessing any private state (instance variables) at the moment, the instance method leaves you with the flexibility to do this in the future without changing the public interface of your class.