Tip: Adding version checking to your external code library
Friday, October 24th, 2008Since version 1.0 of a code library that I’m sure you’re tired of me talking about came out, I have been making steady updates, some of which break legacy code. I was also having trouble keeping track of which version of the library a particular demo was written for. In order to make sure that the new code library doesn’t cause unpredictable results for the old implementations I added a version check to the main class.
This version check is very simple. It checks a version number in the client code against a version number of the library (or external classes) when the main class of the library is initialized. It is also completely optional (so average users don’t need to mark up their code with version numbers).
Here’s an example:
Say you normally initialize your library using:
MyLibrary.initialize();
Which calls the initialize method:
public static function initialize():void { // initialize library here }
If the external code changes unexpectedly (say through an SVN update) this could cause problems that are difficult to trace. The solution is to modify the initializer to match the client code version with the initializer version.
public static const VERSION:String = "1.6"; public static function initialize(versionCheck:String = VERSION):void { if (versionCheck != VERSION) { throw new Error ("The version check failed! This library is version " + VERSION + ". Update your code or GTFO!"); } // initialize library here }
And when you run the initializer, use the version number you’re expecting.
MyLibrary.initialize("1.6");
Some things to notice with this approach:
- I used a string instead of a number for the version number so that it would allow for sub-sub version numbers and other markers, e.g. “1.6.24 beta r545″
- Because there is a default value for
versionCheckin the initializer, providing a version number is optional. UsingMyLibrary.initialize()will still work and throw no errors. - Unfortunately, there is not much you can do if the version numbers don’t match except to warn the client that the external code has changed. Still, I’ve found this to be very useful.
The code for my initializer in its entirety after the jump…
(more…)



