开发者

Does the logic behind objects matter?

When working on the early stages of a console-based Python remake of the classic game 'Snake', someone submitted a patch to spawn food at random locations. The code defined a Food class which worked fine, but the logic behind it seemed a little weird.

I think we should delete the food once it's been consumed, then create another one. However, this person simply moves the food to a new random location once it's开发者_JS百科 been consumed. While the latter seems illogical to me, it seems to do the exact same thing, maybe even more efficiently.

My question is: Would it be better to use the former logic, or the later, or am I simply nit-picking over nothing?

This all started at: https://bugs.launchpad.net/snakes-game/+bug/628180


Either is fine - within certain common-sense boundaries.

The latter approach will save re-allocating the object, so recycling it in this way will be more efficient - the gain is likely to be irrelevant in your particular example though unless heap fragmentation is a concern (e.g. on an embedded app with very limited RAM).

The danger with recycling is that the object may retain some vestige of its former state, so may not behave in the same manner as a new object would - in your case the logic is simple, so there is little danger, but with more complex objects this could become significant.

So in general I'd suggest the "create a new object" approach (it follows the principle of "least surprise", and will be less likely to confuse other programmers who come to work on the code) unless there are performance implications (e.g. on an embedded application like a phone where you have very limited resources and don't want a fragmented heap), in which case the "re-use an existing object" may be a smart solution.


I believe both solutions are fine. Relocating the food to another location is brobably less error prone in memory management terms, but due to garbage collection, you shouldn't care about that too much.

I'd argue, while instantiating a new food object is more logical, and closer to the real life model, relocating is more efficient.


The main issue as far as OOP is concerned isn't so much whether the food re-instantiates vs. relocates, but rather that this behavior remain transparent outside of the object. The game engine should be telling the object "you've been eaten" and such, but how the object handles that internally shouldn't be known to the game engine. If, internally, the object maintains a singleton of "food" and the "consume" method simply re-forms the food object with new values, that's fine. That's all internal to the implementation of "food" and just shouldn't be known outside of that class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜