What Price Protection in Programs?
/I got a lovely question from one of our students today. He is presently working on our "Pick Up the Crew" game coursework and is using objects to manage the items on the screen. The question concerned protection of the data members inside the game objects. If you are writing software for a bank you need to be careful to make sure to carefully manage access to data inside your objects, since you don't want naughty programmers fiddling with account balances. But in a game you don't care so much about this kind of protection. There is nothing particularly important about where on the screen a sprite is drawn.
The questioner was asking if it is OK for a sprite to expose its position information in public data so that other sprites could find out where it is on the screen and check for collisions with it. This is a good idea from a performance point of view (if we are really worried about such things) because it provides quick access to the position information. But is it a good idea from a programming point of view? Should we worry about protecting data inside things like game sprites?
To me this is the wrong question. I don't like using public properties like this because it can introduce dangerous dependencies. If I decide to change the way that I manage sprite position I'm going to break all the other objects that make use of this information directly to work out whether or not they have collided.
From a collision point of view I reckon it is best if each sprite exposed a method (perhaps called CheckCollision) which could be used to see if it has collided with something else. Then if you change how the sprite stores its position on the screen you can just update the behaviour of CheckCollision so that nobody outside your class is affected by the change. There may be a tiny performance hit with this approach, but the chances of introducing bugs are much reduced.