Game Development Reference
In-Depth Information
else if (rand < 0.75f)
moveTo = CGPointMake(moveDistance, -moveDistance);
else
moveTo = CGPointMake(−moveDistance, -moveDistance);
// Move quickly:
[self moveAway:0.1f position:moveTo];
}
return isTouchHandled;
}
I decided to improve the move logic by extracting the functionality into a separate
method. The straightforward way would have been to just copy the existing code from
the update method to the ccTouchBegan method. However, copy-and-paste is
evil. If you join the Cult of Programmology, be aware that it's considered a deadly sin
to duplicate existing code.
Caution Using copy-and-paste is very easy, and everyone knows how to do it,
which makes it so tempting. But whenever you duplicate code, you duplicate
the effort needed to change that code later. Consider the case where you duplic-
ate the same sequence of actions ten times and you need to change the duration
of the action sequence. You can't change it just once; you have to change it ten
times now, and more importantly you have to test the change ten times because
you might have forgotten to apply the change to one of the ten places. More
code also means more chances of introducing a bug, and since this bug will
possibly happen in only one of ten cases, it'll be harder to find as well. I've had
the pleasure to work with a project that was 30,000 lines of pretty much identic-
al code copied and pasted hundreds of times. All in one file. Don't go there, or I
will haunt you! To avoid copy & paste style programming, I suggest to take the
DRY principle to heart. DRY stands for “Don't repeat yourself,”and the prin-
ciple is described at http://c2.com/cgi/
wiki?DontRepeatYourself .
Using methods to extract common functionality, exposing what needs to be flexible as
parameters, is a very simple task. I hope that the moveAway method in Listing 5-14 il-
Search Nedrilad ::




Custom Search