NetNewsWire 2.1 beta Yet Another Mac OS X Application List
Mar 24

A new example of the evil of global variables, and state assumptions

Tech Add comments

I added a simple voting mechanism to ajaxian.com a few months ago.

Since Ajaxian runs on Wordpress the pattern for this work was:

  • Search for voting plugins
  • Weed through the million plugins
  • Find the best one for our needs
  • Go through the plugin code and optimize it

This time was no different. We based our work on the Votio plugin, and tweaked things so the plugin wasn’t doing unnecessary calculations all the time.

The biggest sinner was the functions that take no variables.

As the pages are generated, they go through The Loop, where you get all of the blog entries given to you. We need to generate the ajax ratings form for each item, and to do that we just needed to add:

votio_ballot_box()

That function would access a global (gotta love PHP and “global $foo” :/) to get the current post object. Sounds fine right? We are in a loop of posts. We want to get the post.

It works at first, but what about if things change. For example, we want to do caching, and it is nice to dump out HTML that we can read in, instead of calculating these forms all of the time. In this case, the cache loader does NOT know about the loop of posts, as it is dealing with just HTML that it reads from cache.

I changed the API to be: votio_ballot_box($postId), and in The Loop I spit that out, so now when the cache is loaded it loads “votio_ballot_box(23)” and all is well.

A simple change. A stateless function. Now it is a lot more flexible.

One Response to “A new example of the evil of global variables, and state assumptions”

  1. analogueboy Says:

    so far off topic, but i couldn’t find a more applicable post; now you’ve worked with ruby and enjoyed their way of working, what java web app framework would you use if you had to work in java on your next project?

    I spend all my time in java-land and find that people here are more concerned with ridiculous amounts of flexibility in designs rather than getting things done. I’ve started working with trails to try DDD and I like what i see so far, would you recommend tapestry after your experience on TSS, or would you still take the webwork route?

    again, apologies for asking a questions on your blog, but there are very few forums left that aren’t full of trolls…

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: What are the first four letters in the word British?