I have a class responsible for handling the physics side of collisions. When the collision detector spots a collision, it notifies both entities in the collision to take care of gameplay. It also notifies the PhysicsGenerator to take car of the physics of the collision.

I don't know if it's possible to avoid type checking in the handleCollision() method of PhysicsGenerator. What I wanted to do is apply a force on both entities in the collision to push them backwards. But I can only do this if they are MovingEntities. What if one of them is a StaticEntity? In this case it should be treated differently. I don't know how I can do that without using instanceof quite a lot.

How is this usually handled?


1 Answer 1


The general solution to doing things without type-checking is to move that functionality, in some way, behind an interface.

In this particular case, if both moving and static entities in your physics world shared a common IPhysicsBody interface that supported the ApplyForce method (or was the parameter to such a method), you could apply forces in your collision handling to all entities. Static entities would simply implement ApplyForce such that it did nothing, to reflect their inability to move in response to forces.

In some cases, having "empty methods" mandated by a base class or interface in a subclass is a sign of a poor class hierarchy design. It's hard to say whether this would make that the case for your code without knowing more about it. But that said, another approach is to do away with the concept of static and moveable objects at all, and just make moveability a property: a flag or a special value of mass that represents "infinite mass." Then you simply check for this ApplyForce and early-out. The advantage to this approach (other than a simpler/no hierarchy) is that you can temporarily make objects immobile if needed, which can be helpful.

  • \$\begingroup\$ Currently the applyForce() method is in MovingEntity. I thought about doing what you suggest: moving it up to Entity, making it abstract and having the implementation in StaticEntity do nothing. But I thought that 'conceptually', a class having a method with no implementation is somewhat inelegant. Is it something done frequently in game dev and programming generally? Is it considered okay? \$\endgroup\$
    – Aviv Cohn
    Jun 21, 2014 at 0:51
  • \$\begingroup\$ It can be a sign of a weak design, but not always. I'll update my answer with another option. \$\endgroup\$
    – user1430
    Jun 21, 2014 at 0:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .