Alex Rivera | Logout

Can an object remove itself? How?

Asked 2011-09-01T12:46:10.340
11

I'm trying to write a simple ball game, and there's several turns (ie., ball lives). The ball "dies" when it passes the bottom border of the screen. What I have so far works, but doesn't seem to be the proper way to do things:

if (ball.getY() > bottomOfScreen) {
  ball.die();
  remove(ball);
}

The die() method basically fades the ball's colour slowly (dark_gray -> pause(50) -> light_gray -> pause(50)), but doesn't actually do anything useful.

The remove(), obviously, gets rid of the ball from the screen, which is what I want. It makes sense to me for this remove() to be a part of Ball's die() method, as opposed to it being a separate method call in the main program -- but I'm not sure how to go about this?

Can an object delete itself? And, if it can, is object suicide better than object murder, from a philosophical/methodological point of view?

Thanks!

Edit
Report

1 Answer

1

There is presumably some object (e.g. the Screen, or the ViewRenderer in Johan's example) that holds a reference to the Ball, and removing this reference has to be done by the Screen ("object murder"). "Object suicide" amounts to Ball passing a message to the Screen asking to be "murdered".

Since it is the Ball that knows when it has passed the boundary, it makes sense to me (without knowing the details of your design) for the removal to be initiated by the Ball. Then the Screen can find out about this change by one of several means:

  • The Screen can poll the Ball.
  • The Ball can hold a direct backward reference to the Screen, which creates an unfortunate circular dependency.
  • The Ball can hold a reference to the screen via a BallObserver interface. This is an application of the observer pattern.

The first is simplest, and this makes it a good choice if it fits naturally into your mechanism for painting the screen. The third is more flexible in principle, but you might not need this flexibility in practice. The middle option might be OK in a simple program, but you should probably consider it as a step on the way to the third.

And if you don't have a Screen (or ViewRenderer, or whatever) object and really mean "a separate method call in the main program" then you should probably reconsider your design.

answered 2011-09-01T13:48:20.987

Your Answer