The human behind Windmill - A companion for seamless iOS development.
Here Be Dragons Don't Abuse The If
Most of us would go mental having a dragon as a pet but what's even more fun is creating your own!
Now, designing your own dragon will most likely make you over excited causing you to simply dump code.
Take a look at the IndecisiveDragon class. This class has a breath property which is merely an int acting as a flag to designate the type of breath your dragon has. Having an int for that purpose not only poses a risk for arbitary breaths (thus making it harder to debug) but makes extending the dragon with a new breath even harder. Not to mention how scary your dragon can grow. And you don't want that dragon turned against you.
In order to cope with the different types of breaths the #breathe method has a switch statement which depending on the value does something different. The important thing to notice is that a dragon has a breath therefore the #breathe method merely executes one branch per dragon (1 dragon - 1 breath, more on multiplicity later)
Finally, there is a naive default constructor which is used to just create a dragon and be done with it. Most likely this happens at a later stage when adding a method to the IndecisiveDragon class that has nothing to do with breath(s) or even the dragon itself in most cases.
Say hello to the MightyDragon. This dragon clearly states it's relationship with a Breath type which not only ensures type safety among breaths but allows you to extend your class without modifying it making it easier to choose between different breaths. Notice how you delegate the code to the breath thus in essence applying polymorphism since every breath is implemented differently.
When creating a MightyDragon you are forced to explicitly choose 1 breath which the dragon shall have. (In OO terms this is actually the Strategy design pattern)
What's also important to notice is how the HeavyFireBreath class defines an extra method related to the #breathe which otherwise would have ended up either inside your dragon class or part of the switch statement.
Leave your comment below on how it helped you make your life a bit better without another if
Disclaimer: Again this is a trivial example. FireBreath, PoisonBreath and NoBreath aren't really that different since they all return the damage dealt, so a single class would suffice. In any case the breath interface allows you to extend your dragon (adding custom breaths) without modifying its internal(s) [organs].