OOP Lesson - Duck Typing - Making code more amendable to change

_config.yml

Hi folks

Consider the code below:

Watch out for any situation where you are doing this:

If you are unsure of what type you are receiving, and if you have to ask: is it a gun? If so then do this. Is it a helicopter? If so then do that? etc. If you have to do this then you are missing something.

You probably need to “implement an interface”. Ok, so what does that mean? It means that you want to turn the above code, into a more simplistic version. You need to change those classes so that you could do something like this:

So that no matter what type the weapon actually is (gun, helicopter, F16) then it still knows exactly what to do. Granted, each of this objects (gun, helicopter, F16 etc) will have to have to be able to receive the “ready_weapon” message. This means that those objects will have to have a method within them which is called: “ready_weapon”.

This approach ensures that your code is much more amenable to change.

Written on April 23, 2017