Skip to content

Wrapping loose variables and functions in Add-ons

We (AMO Editors) have traditionally rejected updates or nominations on add-ons that don’t follow the wrapping rule for variables and functions. This is an important rule IMO because the possible compatibility conflicts are very real and possibly damaging to user experience. Enforcing good user experience and code quality is part of our responsibility as editors, so I think this rule should not be removed or lessened in any way.

This discussion came up due to a denied update for Text Formating Toolbar I was requested to come up with a POC that demonstrates how name conflicts can cause problems, so I created this add-on, which conflicts with Text Formatting Toolbar using seemingly harmless code. Here’s the link:

Name Conflict

If you install this with the Text Formatting Toolbar, you’ll notice that the bold, italics, code and color features are broken.

Here’s the code in my overlay:

  function() {
      function () {
        formatItalics = "i";
        formatBold = "b";
        formatColor = "white";

        formatCode =
          function(aString) {
            if (typeof(aString) != "string") alert('Invalid Code!'); }

As you can see, it’s fairly simple. The load event and setTimeout call are only used to make sure that it is the other extension and not this one the one that experiences the compatibility problems. If two add-ons use the same names in the global scope, then one is going to experience problems in one way or another. There’s nothing more to it.

Obviously I can intentionally create an add-on that causes conflicts with any other add-ons, but I hope you see past this and realize that the code I posted could very well be written by another author who is unaware of the rules we enforce. This is what we look after, and this is why we should reject global namespace pollution in almost all instances.

{ 2 } Comments

  1. Axel Hecht | 2010/01/24 at 10:46 AM | Permalink

    What’s the right way? Use a ‘var’ in front of the variables in the anonymous function?

  2. jorge | 2010/01/24 at 1:53 PM | Permalink

    There’s no bullet-proof way of preventing name collisions.
    The simplest and most effective way of namespacing Javascipt in add-ons is to choose a name that is relatively unique. So, if your add-on is named “Text Formatting Toolbar”, then “TFToolbar” or “TextFormattingTB” should be good enough.

Post a Comment

Your email is never published nor shared. Required fields are marked *