Page 116 -
P. 116

functions



           Don't duplicate your code...

           When you need to add a new feature to a program that’s similar to some
           other code in the program, you might be tempted to just copy and paste
           the code.                                                        You'll find that code bloat is
                                                                             common in lots of programs,
           In practice, that’s actually a pretty bad idea, because it can lead to code   even code written by
           bloat. Code bloat means that you have more code in your program than   professional programmers.
           you actually need. Your programs will get longer, and they’ll get a lot
           harder to maintain.



                            Here‛s the printout of the tic-tac-toe
                          game. If you really want me to change the
                         colors of the crosses, I‛ll just need to replace
                        the code that displays each of the 9 squares. That‛s
                        the same code in 9 different places. Oh, and if you
                          want me to change the 0s...






          ...Reuse your code instead


           Programming languages all come with features that allow you to reuse
           code. So what’s the difference between copying and reusing code?

           If you copy code, you simply duplicate it. But when you reuse code, you
           have a single copy of the code that you can call in all the places that
           you need it. Not only will your programs be shorter, but it also means that
           when you amend code, you will need to change it only once and in one
           place only.



                                  So you want a new gravity-bomb
                                  launcher added to each of the
                                  star-fighters? No problem. I‛ll change
                                  a few lines of code and every craft in
                                  the fleet will be updated.




           So code reuse is a good thing. But how do you do it?




                                                                                        you are here 4    81
   111   112   113   114   115   116   117   118   119   120   121