Managing Your Code


In this section, we'll discuss methods and options for storing, writing, and positioning your code. In Flash 8, there is often more than one way to perform the same action — if you don't thoroughly think about why and where to place your code, you can run into trouble quickly. Using the following methods and suggestions will help you avoid common mistakes.

Using Replace in the Actions Panel

Writing online applications in Flash often requires you to write a lot of code. While writing code, it is easy to name an object or variable without thoroughly thinking it through. Naming your objects and variables descriptively is a good idea. If you don't, you will find it hard to come back to your files and remember what each object and variable is int0ended for. Using Search and Replace enables you to easily rename poorly or improperly named variables or objects. It enables you to identify and change the incorrect string in one step, leaving Flash to replace all occurrences of the string.

However, there are traps when doing this. The following list contains points to remember:

  • If you change the name of a variable, you must also change each reference to the variable across all timelines.

  • Search and Replace replaces strings even if they make up a larger part of a code string. For example, the line sou = new Sound(); will be modified to the line sit = new Sitnd(); when you replace ou with it. So, if you use this feature, be mindful of the implications of searching for strings existing within other strings. A good method of avoiding this problem is to use a space whenever possible, remembering to replace the initial space with another in the replacement string. This step is necessary so your code formatting isn't modified.

Step through the following example to learn how to use Search and Replace to modify a block of code:

On the CD-ROM 

You will find component_definition.fla in the ch32 folder on this book's CD-ROM. Copy this file to a location on your hard drive. We use this example code in a Search and Replace function.

  1. Choose File Open and browse to the folder on your hard drive where you saved component_definition.fla. Highlight it and click OK.

  2. Select frame 1 of the actions layer.

  3. Open the Actions panel (F9, or Option+F9 on Mac).

  4. Open the Replace dialog box by doing one of the following:

    • Choose Replace from the options menu of the Actions panel.

    • Click the Find/Replace icon on the toolbar of the Actions pane.

    • Press Ctrl+F (Windows) or z+F (Macintosh).

  5. Type [Author name] into the Find what field.

  6. Type your name (for example, "John Smith") in the Replace with field. You will be replacing "[Author name]" with your name.

  7. From here you can search for each instance of the string before choosing to replace it. To do this, click Find Next. However, if you want to simply replace all instances of "[Author name]," choose Replace All. For this example, choose Replace All.

Choosing Find Next is a good method for overcoming the problem when a string is found within a larger string. You can choose Find Next; when it finds the string on its own, you can replace it by choosing Replace. If it finds the search string within a larger string, simply choose Find Next to move forward.

Tip 

You can also use the global Find and Replace feature in Flash 8 to search your entire document for specific ActionScript terms. Choose Edit Find and Replace, and make sure the ActionScript check box is selected. Clicking one of the found results takes you directly to the script where the term was found.

How and Where to Place Your Code

There are several ways to position your code effectively, but first there are two considerations to make. On one hand, your code needs to be effective and work well; it must be positioned properly in order for the application to work successfully. On the other hand, you need to make the application easy to build and edit. It needs to be quick and simple in order to modify sections without being laborious and taking up valuable time better spent coding.

The project requirements also dictate how you place your code. We use the scenario that follows to explain some good coding concepts and how and where to place your code.

You are creating a coloring book aimed toward children. The requirements state the application must have a paintbrush tool with different brush styles and sizes, a line tool with different widths available and a stamp tool used to place user-defined images on the drawing canvas. Each of the tools has a corresponding button and a range of options used to modify the properties of the tool. The user clicks on the canvas to start drawing or stamping. Building this application would require a combination of different functions. Functions can be grouped into the following two main categories:

  • Multipurpose functions: A multipurpose function can be used many times and by more than one source. A multipurpose function should be written in the most generic way possible, but still meet its criteria. The coloring book application would benefit from a multipurpose function used to modify the cursor. For example, when the user clicks the line tool, the function changeDrawingTool() might be called with the string "line" passed as the parameter. This function would then call changeCursor() to handle the cursor being changed and modifyOptions() to modify the options panel, which would reflect the current tool being used.

  • Chain functions: The most effective functions are self-contained, perform one specific task, and can be used by many sources. However, there is an exception to the rule: chain functions. Chain functions group many other functions to perform several actions at once. Using chain functions enables you to write neater code and make it easier to understand.

    An example of a chain function for the coloring book application would be startDrawing(). This might call the following functions: getColor(), which gets the current color ready to draw; followMouse(), which is used to trace the path of the mouse; and draw(), which actually draws the path to the canvas using values from followMouse().

    A major benefit of using chain functions is you split up code into smaller chunks, which can then be easily accessed by other methods. For example, the startDrawing() function could have all of the code from the getColor(), followMouse(), and draw() functions within it. However, it would make the getColor() function inaccessible. This function could be used for more than one purpose. For example, if you passed red, green, and blue values to the function, it could set the color for the user, rather than just retrieve the value the user has set.

Cross-Reference 

The Hangman game discussed in Chapter 31, "Creating a Game in Flash," uses many functions chained together within an organized event model.

Note 

After you start to write more sophisticated code, such as chain functions, you may want to explore the concepts of true object-oriented programming in ActionScript. In this edition of the Flash Bible, we've gone to great lengths to replace many code examples with object-oriented design patterns.

Centralized Code

There are many places you can write code in Flash: in a frame, in and on Movie Clips, and on buttons. Your code can interact with any other object within the current movie structure including all levels and nested objects. This makes ActionScript an easy language to use for referencing and modifying objects from anywhere within a movie structure. It also allows for poor coding placement, however. It is very important to take note of where you place your code. "Spaghetti code" is a common term to describe poorly placed code residing on multiple timelines and interlinked in an unclear way. It is quite easy to run into the trap of creating such code.

Centralized code is the key to making an application easy to use and edit. Centralized code does not necessarily mean all of your code should be written on frame 1 of the Main Timeline. Creating centralized code means making observations about what the code is being used for, where it applies, how often it will be used, and how many objects will use the code.

Creating centralized code is different for each project. Here is a list of key concepts to follow when centralizing your code:

  • Reusable code: Determine if a certain block of code is going to be reused by more than one object. If so, it is suitable for turning it into a function or a method, or possibly even a listener for objects that broadcast events.

  • Same code, multiple objects: If a block of code is going to be used across a range of objects, such as buttons, you should place the code in a function and execute it from each button.

  • Function parameters: Use functions to your advantage. If you have a block of code repeated across a number of objects referring to the objects' properties, you can centralize the code and make it much more manageable. Create a function in a central location and set up parameters to parse needed information about each object to the function. When you want to modify the block of code, you only need to do it once instead of on every object.

Naming Conventions

A naming convention is a method and style used to name objects, variables, frames, symbol instances, and many other aspects of Flash development. You can have different naming conventions for each area, such as frames and variables. However, you should keep this practice to a minimum and use it only if necessary. There are common naming conventions used by most ActionScript and JavaScript code writers. Here is a list of rules that you may use to help you to create a naming convention:

  • Alternate capitalization: The first word is entirely lowercase, all subsequent words start with a capital letter, and all spaces are removed. This method is also known as InterCaps or "camel hump" and is used by many programming languages. ActionScript's predefined functions also follow this rule. A good example of this is the method name createEmptyMovieClip() of the MovieClip object — notice that the E, M, and C of this keyword are capitalized. This rule can be applied to objects, variables, frame names, and symbol instance names.

    Caution 

    Flash Player 7 and higher force case-sensitivity in ActionScript code, regardless of whether it's ActionScript 1.0 or 2.0. Be extremely diligent about adhering to your own naming conventions in code.

  • Descriptive: Creating successful names for your ActionScript elements is a careful process. The most effective names are descriptive, making them easy to read in context and easy to understand the next time you read the code. Try to shorten names as much as possible while keeping them descriptive. For example, a function used to get the current local time could be named getLocalTime because it is descriptive and short.

  • Class capitalization: Many coders don't use this rule, but it does help when you are creating large applications with dozens of variables, functions, and objects. You can capitalize every word of your class names rather than every subsequent word after the first. This makes it easy when you are coding to distinguish between variables and functions, or objects.

  • Acronyms: Using an acronym when you are creating global variables, functions, or objects is a great idea. This ensures when you mix your ActionScript with someone else's you won't have conflicting names. Your acronym should be short and have something to do with the project you are creating. For example, if you are creating an online e-mail reading/sending/writing program named FlashMail, you might want to add FM to all variable names, functions, and objects, such as FMComposeNewMessage.

Commenting

A particular problem with writing ActionScript is returning to your code to modify it at a later date — most of us don't have computer-like memories. Commenting your ActionScript while writing it is an excellent idea that overcomes this problem by helping you remember how the code is constructed and/or works. It may take slightly longer to write your code with commenting, but it is worth the trouble. Follow these rules to effectively comment your code:

  • Blocks of code: You don't need to comment every line in your code. Rather than doing this, comment each block or the different sections of your code. If the ActionScript is obvious, such as setting a MovieClip object's X position to 10, you wouldn't write // Set the movie clip's position to 10. A more effective comment would be // Align the movie clip with other objects.

  • Natural language and punctuation: Your comments should contain all punctuation and grammar, as if you are writing a formal letter. It is quite easy to write something that makes sense to you but not to others, but using punctuation ensures that your comments are easy to understand to everyone who reads them.

  • Be descriptive: It is important to be as descriptive as possible. This also helps you remember what your code is doing when you come back to it.

  • Multiline or single-line comments: There are two methods to comment in ActionScript. You can use /* comment in here */ or // comment here. The first method is used to create multiline comments; you can enter down to a new line and what you type will still be commented. The second method is used for single-line comments. A good practice is to reserve multiline style commenting for more important comments or if you want to catch the reader's attention.

Strong (or Strict) Typing

As you have seen earlier in this chapter and other chapters in the book, the ActionScript 2.0 language can use strong data type declarations. If you are starting a project from scratch in Flash 8 for Flash Player 6 or higher, we strongly recommend that you try to use ActionScript 2.0 and strong typing. This simply means that you declare variables with data types. If you try to perform an illegal operation with a specific data typed variable or object, Flash 8 will inform you in the Output panel — this is definite bonus for developers during the debugging process.

Add the code shown in Listing 32-2 to frame 1 of an otherwise empty Flash document. If you click the Check Syntax button in the toolbar of the Actions panel, you'll see the following error in the Output panel:

 **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 1: Type mismatch in assignment statement: found Number where String is required.      var nPercent:String = (nLoaded/nTotal)*100; 

Listing 32-2: A Sample Script Using Strong Data Typing

image from book
 var nLoaded:Number = this.getBytesLoaded(); var nTotal:Number = this.getBytesTotal(); var nPercent:String = (nLoaded/nTotal)*100; 
image from book

The error message tells you that the expression used to set the value of nPercent returns a Number data type, not a String. If you change the data type of nPercent to a Number, then the code will not return an error:

 var nPercent:Number = (nLoaded/nTotal)*100; 

Declaring data types with your variable declarations forces you to think clearly about how your code will be used.




Macromedia Flash 8 Bible
Macromedia Flash8 Bible
ISBN: 0471746762
EAN: 2147483647
Year: 2006
Pages: 395

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