Saturday, July 21, 2007

 

Change of Heart about Kick-offs

For a long time, I've had a couple of "kick-off" snippets in my iSnip file that form a framework for kicking off a script. They look like this:

Document Kick-off

if (app.documents.length == 0) { exit() }
processDocument(app.documents[0]);

function processDocument(aDoc) {

} // end processDocument

Selection Kick-off

if (app.documents.length == 0 || app.selection.length == 0) { exit() }
processSelection(app.selection[0]);

function processSelection(sel) {

}

Change of Heart

I used to like this approach. Detecting immediately that the application was not in the state of interest for the script and exiting just seemed an appropriate way to get rid of those conditions without cluttering up your script with an extra level of indenting.

But there are two problems with this:
  1. There is no extra level of indenting since I switched to doing all the processing in a function. That thinking dates back to the days when I was writing monolithic scripts that did all (or most) of the work at the global level.
  2. When you use exit(), you don't just exit the script, you exit the scripting system. So, if you are trying to string together a series of scripts, the use of exit by one script prevents any more scripts in the string from running.
As a result of these two realizations, I have changed my snippets to look like this:

Document Kick-off

if (app.documents.length > 0) {
  processDocument(app.documents[0]);
}

function processDocument(aDoc) {

} // end processDocument

Selection Kick-off

if (app.documents.length > 0 && app.selection.length > 0) {
  processSelection(app.selection[0]);
}

function processSelection(sel) {

}
Notice the change from logical OR to logical AND in the selection kick-off. This structure works because if there is no document, the logical expression evaluates to false without the need to evaluate the second part of the expression, which would, in that case, cause an error.

The extra level of indenting that I used to worry about lasts just one line now, so it is not nearly the big deal it used to be.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?