The Three R s: Readability, Reusability, and Reachability

     

The Three R's: Readability, Reusability, and Reachability

Each Flash programmer tends to develop his or her own style of writing, organizing, and commenting programs. Companies that employ Flash programmers also have different standards. However, whatever your individual style, you probably want to write code that is readable, reachable , and perhaps reusable. The longer and more complex your programs are, the more important it is to think about these goals before and as you write.

Readability: Writing Readable Code

When you go back to change, enhance, or debug a program, it's nice to have code that you can decipher without too much strain on your eyes or brain. Readability is partly just a matter of spacing, indentation, and capitalization. Comments can also add a lot to readability, as can the use of meaningful names for functions, variables , arrays, and objects. Finally, the best (and hardest) way of making code more readable is by solving coding problems in more elegant, simpler ways.

Spacing, Indentation, and Capitalization

With few exceptions, ActionScript is very flexible about spacing and indentation. FP6 (and FP7 when playing movies published for FP6) is also forgiving when it comes to capitalization.

For example, when playing movies published for FP6, these two functions look the same to the ActionScript interpreter (the software that interprets SWF files):

 function addonetobasescore(basescore){return basescore+1;} function addOneToBaseScore (baseScore) {      return baseScore + 1; } 

Whitespace, capitalization, and indentation make the second significantly more readable, and thus make it easier for you to understand and edit your program.

Remember, however, when publishing for FP7, capitalization affects the way your program works, not just the way it looks.

Adding Comments to Your Script

Just formatting the code is seldom enough to make it clear what's going on in a complex program. Comments are usually necessary, too. Single-line comments are marked by double slashes :

 // input: base score, returns: one more than the base score 

A comment can also follow code:

 baseScore += 1; // baseScore declared frame 1, main timeline 

Enclose multiline comments like this:

 /* ADD ONE TO BASE SCORE Michael Hurwicz  - January, 2004  www.greendept.com baseScore is an integer */ 

Some people prefer double slashes on every line because they make it clear that each line is still part of the comment:

 ///////////////////////////////////////////////////////////////// // ADD ONE TO BASE SCORE // Michael Hurwicz  - January, 2004  www.greendept.com // baseScore is an integer ///////////////////////////////////////////////////////////////// 

In the Script pane, comments are color-coded, so you know where they start and stop. You can customize the color coding by selecting Edit, Preferences, ActionScript, and clicking in a color swatch in the Syntax coloring section. A selection of color swatches pops up, and you can select one. In this way, you can use colors for displaying foreground, background, keywords, comments, identifiers, and strings.

Creating Readable Names

You've seen that ActionScript programs have several types of elements that require names, such as functions, arrays, objects, and variables. What makes such names readable?

You've already encountered one aspect of readability for names: capitalization. Reading addOneToBaseScore is easier than reading addonetobasescore . Traditionally, by the way, most names in Flash begin with lowercase letters . An initial capital indicates a class.

Another good technique is to give things names that you (and others, if necessary) will understand intuitively. For instance, you probably won't have to examine the details of the addOneToBaseScore function to remember what it does.

Simplifying, Standardizing, and Optimizing Code

The best way to make your code more readable is to come up with straightforward ways of accomplishing your programming goals. Simple code will make your life as a programmer much easier. Of course, creating masterfully elegant code is easier said than done, but it's a worthy objective.

Better Coding with Pseudo-Code

One tool that may help you write simpler, more elegant code is pseudo-code. Pseudo-code represents your program, or some part of it, in your own words, but with as much specificity and detail as possible, and by trying to follow the flow and layout of the program as you envision it. Pseudo-code enables you to focus on the logic of your program, without getting bogged down in the mechanics of ActionScript. It allows you to mentally experiment with different approaches to a problem, without wasting time implementing approaches that you ultimately reject. When you do start coding, the pseudo-code serves as a detailed outline for the finished product, helping you stay on track.

Here's a very simple example, taken from leglift.fla, which is discussed in the next section. The central function in leglift.fla is lift() , which is called repetitively to gradually lift a leg off the ground or lower it back down. It can also stop the leg from moving. Movements are accomplished by rotating the leg at the hip. Here is the pseudo-code:

function graduallyApproachGoal() receives a parameter ( goal ).

If the current rotation of the leg is less than goal , increase the rotation of the leg one degree.

If the current rotation of the leg is greater than goal , decrease the rotation of the leg one degree.

If the current rotation is the same as goal , do nothing. (The leg will not move.)

You can see this function implemented as lift() on page 451 in the next section.


Trying to standardize your code is also helpful so that you can use the same techniques or syntax over and over. You'll understand blocks of code at a glance because you'll be so familiar with the techniques and syntax involved.

Simpler code also usually performs better than more complicated code. Because you will, of course, standardize on your best code examples, standardization is likely to make your program run better all around. Concise coding will also permit faster debugging and easier editing.

In some cases, however, a conflict occurs between fast code and easy-to-read code. In those cases, one approach is to actually use the fast code in the program but retain the easy-to-read code as a comment.

Reusability: Modularizing Code

Most programmers reuse code to some extent. After all, programming is essentially problem-solving. If you've solved a problem before, why reinvent the wheel? The techniques used to achieve reusability also make code more readable and easier to debug. Any time you find yourself typing similar code over and over, or cutting and pasting code, look for a better approach.

The two main vehicles of reusability are functions and objects. Both allow you to package functionality in modules that you can reuse both within a program and among multiple programs. Arrays can also play the same role, if you want access via numeric indices.

In addition, packaging functionality in functions and objects makes your code more readable. For instance, suppose you find this code inside an "enter frame" event handler attached to the left leg of a figure:

 degrees++; if (degrees < 30) {      _rotation++; } 

You know that every time the movie clip enters a frame, the ActionScript interpreter is going to do whatever this code says. But what is that, exactly?

Compare that example to the following line, which invokes a lift() function, passing it an argument of 30.

NOTE

An argument is data that you pass to a function, enclosed in parentheses after the function name .


 lift (30); 

You don't need to be a genius to guess that the figure is probably lifting its left leg, and that the argument, 30, has something to do with how much it's lifting the leg. You get that increase in readability just by putting the less intuitive code in a function with an intuitive name.

Now, let's make that leg part of an object named guy , with a leftLeg property. The leftLeg property is also an object, with a lift() method:

 guy.leftLeg.lift(30); 

It's practically a full sentence , with subject, object, verb, and adjective: A guy is lifting his left leg.

How do you make the leg part of an object named guy ? You take advantage of the fact that movie clips are objects. Here, guy is a movie clip, and leftLeg is a clip within it. The lift() function becomes a method of leftLeg when it is defined as a property of the leftLeg object.

Both lift() and guy.leftLeg.lift() assume that somewhere else in your program you have defined a function called "lift" that does something similar to the less intuitive code shown on page 451. If you look at that function definition, you can get a more precise idea about what lifting means in this context ”namely, that it has to do with rotating the clip:

 function lift (degrees) {      if (_rotation > degrees) {           _rotation--;      } } 

Add a comment to the function definition ”"used to lift leftLeg" ”and you have some very readable code.

The sample program leglift.fla shows a slight elaboration of this approach. It adds a second part to the lift() function so that the function lowers the leg if _rotation is less than degrees and raises the leg if _rotation is greater than degrees . If degrees equals _rotation , the function does nothing; that's the basis for stopping the leg.

 // used to raise, lower and stop left leg      function lift(degrees) {           if (_rotation < degrees) {                _rotation++; // lower the leg           }           if (_rotation > degrees) {                _rotation--; // raise the leg           }      } 

The sample also defines three functions that change the degrees variable, thus raising, lowering, or stopping the leg:

 function raise() { degrees = 20; } function lower() { degrees = 68; } function halt() { degrees = _rotation; } // lift() will do nothing 

These three functions are invoked from three buttons on the Stage. The "enter frame" event handler of the leg clip is constantly executing the lift() function, so the appropriate action is triggered as soon as degrees changes.

Using functions and objects also tends to make you a better programmer. This goes back to the fact that programming is problem-solving, and the first steps in problem-solving are defining the problem domain and defining the problem itself.

In the process of defining objects, you also define problem domains precisely. In the leg lift example, for instance, the domain of your problem is guy.leftLeg . Similarly, in the process of defining a function, you also define the problem. For instance, the previous function defines the problem as lifting the leg a certain number of degrees.

Functions and objects also help you break down large problems into smaller problems. Suppose you want a cartoon figure to walk across a room. A walkAcrossTheRoom() function might be relatively complicated. Perhaps you could write a takeOneStep() function and repeat it until the figure gets across the room. So, what is involved in taking one step? The figure has to swing an arm, move a leg, and move a certain distance forward.

If you keep going like this, eventually you'll come to problems that are small and precise enough to get your mind around and solve. You may start by implementing your solutions as functions. You could then combine these functions into more complex functions, objects, or sections of code. Objects and functions are great problem-solving tools because they help you solve dauntingly complex problems one simple step at a time.

graphics/troubleshooting_icon.jpg

Ready to start programming, but don't know where to start? See the "Troubleshooting" section later in this chapter, page 458 .


Avoiding the supposed complexities of functions and objects is like avoiding the complexities of folders when you're managing email or files on a hard disk. As the number of messages or files grows, the lack of organization begins to hamper your ability to work efficiently . Similarly, objects and functions are basic to organizing ActionScript. They should make your life easier, not harder.

Reachability: Organizing and Centralizing Code

There are two aspects to reachability: the interpreter's ability to find functions and variables at runtime (when your program is running) and your ability to find physical lines of code when you need to edit them.

By bundling functions and variables into objects and classifying objects in different classes, OOP provides the infrastructure that allows the ActionScript interpreter to find what it needs while your program is running. For instance, there is a concat() method (function) for arrays and a concat() method for text strings. In each case, the definition of the method is stored in the class definition, so the interpreter knows just where to look for it and doesn't get the two confused .

There are also scoping rules that determine whether a variable, function, or object in one part of the program is directly "visible" from another part of the program. By centralizing code ”putting as much of it in one place as possible ”you avoid possible scoping problems.

For instance, if all your code is within a single frame, you don't have to worry about scoping. Putting all your code in one frame was sometimes difficult or undesirable in Flash 5. In Flash MX, because of in-line event handlers, it is much easier and generally has few drawbacks. (In-line or dynamic event handlers are defined in frames rather than having to be attached to movie clips.)

For instance, the sample program leglift.fla on the CD is a bit hard to dissect because the small amount of code it contains is attached to several different objects and can be difficult to find. Sample program leglift2.fla centralizes all the code in one frame, making it easier to find and understand. The main change required was using in-line event handlers instead of event handlers attached to movie clips.

In-line event handlers are introduced in "Selecting Frame Actions or Object Actions," earlier in this chapter, page 445 . They are discussed at more length in Chapter 20, in the "Using Event Handlers to Trigger Action" section, page 500 .


For an example of making your code more readable, reusable, and reachable, see unimportant.htm on the CD.


Another important issue is your ability to find and conveniently edit code. In any somewhat complex program, Flash provides many nooks and crannies where you can "hide" code. If code is scattered around in too many places, maintaining your program can become hard.

Suppose you need to add a second argument to a function. The function itself is defined in just one place, so you can change it easily enough. However, you must also find every reference to that function in your program and add a second argument there, as well. If all your code is centralized in one place, you can search on the function name and probably find all the references in minutes. If your code is scattered around in 20 different places, you have a longer, more tedious job in front of you.

Centralizing code is perhaps the most important factor in easy program maintenance. Through in-line event handlers, Flash MX makes it easier to avoid the "scatter-gun" effect that makes programs difficult to maintain.

graphics/troubleshooting_icon.jpg

Have you centralized all your ActionScript and now want to keep it in the Actions panel while working on graphics in other frames? To find out how, see the "Troubleshooting" section later in this chapter, page 458 .


Using Movie Clips to Organize Data and Functions

Prior to Flash MX, nearly every scripted Flash program used movie clips for organizing code. The clips containing code were often " dummy " clips with no graphical content. Although you may still find it convenient to attach code to movie clips from time to time, this strategy is much less necessary in Flash MX than it was in Flash 5. Anything that you would formerly have put in an onClipEvent(enterFrame) event handler (attached to a movie clip) can now go in an in-line onEnterFrame event handler (in a frame). Similarly, there are in-line formats for other event handlers.

When considering whether to attach code to movie clips, think about this: If you have 20 movie clips on the Stage in frame 1 of your movie, you can put an action in the "enter frame" event handler of every movie clip, and the Flash interpreter will execute every one of those actions, round- robin style, before going on to frame 2. Or, you can put one in-line onEnterFrame event on the first frame of the Main Timeline and put all the actions in that one clip. Flash will execute all the actions in the in-line event handler before going on to frame 2. In other words, exactly the same thing gets accomplished, but your program may be 20 times easier to maintain.

Using Timelines to Organize Code

You can also use a timeline to organize code. Each frame can serve the purpose of a function, holding a block of code that accomplishes a particular task. You "invoke the function" with a play() , gotoAndPlay() , or gotoAndStop() action that sends the playhead to the appropriate frame.

At the same time, you can animate, add, or remove movie clips in that frame.

Better yet, put each block of code into a function and just call the function on the frame. This makes each frame more readable. It also allows you to centralize the bulk of the code. For instance, you can put all the functions in the first frame of a single layer.

However, because you must edit code separately in each frame, organizing code on a timeline doesn't really centralize the code. It's almost as tedious to "peek" into multiple frames on a timeline as it is to look in multiple movie clips.

Though still used, this technique is largely a holdover from earlier versions of Flash, which did not support functions. It is a viable technique, especially for simple movies, but it can become a hindrance in more complex ones.

Using the Movie Explorer to Find ActionScript

The Movie Explorer can help you find the ActionScript in Flash source (.FLA) files. Start by deselecting all the buttons except the ActionScript button in the Show section near the upper left of the Movie Explorer panel (see Figure 19.2). The Movie Explorer then displays only movie clips and buttons that contain ActionScript.

Figure 19.2. The buttons in the Show section near the upper left of the Movie Explorer panel determine what kinds of program elements appear in the panel. The far right button displays a dialog that enables you to configure all the items at once.
graphics/19fig02.jpg

For more details about the Movie Explorer, see Chapter 15, "Flash Environment and Tools," page 344 .


The buttons in the Show section in the upper left of the Movie Explorer panel determine which types of movie elements the Movie Explorer displays. From left to right, they control text; buttons, movie clips, and graphics; ActionScript; video, sounds, and bitmaps; and frames and layers . The magnifying glass on the right provides a single panel for customizing all aspects of the Movie Explorer display.

To display the ActionScript in a particular button or movie clip, click on the button or movie clip name in the Movie Explorer display list. The name is highlighted. Then click on the options menu (in the upper-right corner of the Movie Explorer panel), and select Expand Branch. Alternatively, you can click on the plus sign to the left of the movie clip or button icon in the display list. However, you might have to click on several plus signs before you get down to the ActionScript.



Using Macromedia Studio MX 2004
Special Edition Using Macromedia Studio MX 2004
ISBN: 0789730421
EAN: 2147483647
Year: N/A
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net