View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator 2006-11-05 #11 Old  
010a - Creating a utility class
Last edited by Codemonkey : 2006-11-06 at 10:56.
 
If you have some functions you might use anywhere and possibly in different projects, you might want to create util classes from them. A util class is a class available from a global path with static methods only. Flash' Math class is a good example of this.

To create a util class start with an empty class like this:

ActionScript Code:
  1. class MyUtil {
  2. }
Then add your functions with the keywords public and static. Public so everyone can see them, static so everyone can access them through the classname without having to create an object first.

ActionScript Code:
  1. class MyUtil {
  2. public static function MyUtilFunction(params_here):Number {
  3. // do stuff with params and return result
  4. }
  5. }
One benefit of having static methods only is that you acknowledge the functions do not depend on a state, which is the case a lot of the times with class instances (objects). This basically means you will only create one-shot functions that do a specific operation/calculation.

If you want to prohibit people from instantiating a utility class - which would also mean such a people didn't 'get' your utility class - you can add a private constructor:

ActionScript Code:
  1. class MyUtil {
  2. private function MyUtil() {}
  3. }
Here's an example of a complete util class:

ActionScript Code:
  1. class ArrayUtils {
  2. private function ArrayUtils() {}
  3.  
  4. // returns index of an item in array, -1 if it isn't in the array
  5. public static function inArray(array:Array, item:Object):Number {
  6.         [..]
  7. }
  8.  
  9. // tries to remove an item from array and returns whether it worked
  10. public static function arrayRemove(array:Array, item:Object):Boolean {
  11.         [..]
  12. }
  13. }
Usage:

ActionScript Code:
  1. var names:Array = new Array("Bob", "Shirley", "Pete");
  2. trace(ArrayUtils.arrayRemove(array, "Bob")); // traces "true"
  3. trace(ArrayUtils.arrayRemove(array, "Bill")); // traces "false"
  4.