Instance method vs. static method with ref parameter

六月ゝ 毕业季﹏ 提交于 2019-12-12 04:09:10

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9754337/instance-method-vs-static-method-with-ref-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!