jeudi 26 septembre 2019

How to avoid type checking

I am working on a project which has some GameObject. It can be anything a ball, a coin, a plant. And I have to pass the list of GameObject to some other class which renders the objects on-screen.

The GameObjects can be moveable and non-moveable. Some GameObjects can allow passing objects through them(Pervious) and some not. Some GameObjetcs have thrones (which might explode the ball) and some not. Some GameObjects are coins which are collected when the ball hits them.

So I did this -

Class GameObject{

// All things common to both entities. 
// Feilds - hasThrones, canPassthrough, isCoin
...
...
}

Class MovingGameObject extends GameObject implements Moveable{
    moveable logic;
...
...
}

Class FlyingGameObject extends GameObject implements Flyable{
    Flyable logic;
...
...
}

And I now have a List < GameObjects >.

Problem When I am making the moveable objects move, I am doing something like:

if gameobject is an instance of MovingGameObject{
        // do something
}

if gameobject is an instance of FlyingGameObject{
        // do something
}

I know this is bad code. How do I refactor it to not use type checking?

One way I can think of is using lists. But That's not really a way as now what if I want a swimming object now? Then I do have to store in a new list for swimming objects.

Thanks

Aucun commentaire:

Enregistrer un commentaire