How To

Unique vs Common

A little on the topic of naming libraries and functions.

Someone asked me if I could explain why sometimes I tell people to name their functions uniquely and sometimes I don’t.

I get how this is confusing, even though it makes perfect sense to me. Here’s how to remember:

  • What’s yours is unique to your plugin
  • What’s common is unique to what’s common

Okay, maybe that didn’t help. Let’s try a practical example!

I have a plugin called ‘Genericon’d’ which includes the Genericons library inside. In that plugin, I have the following enqueues:

        wp_enqueue_style( 'genericons', plugins_url( 'genericons/genericons/genericons.css', __FILE__ , '', self::$gen_ver ) );
        wp_enqueue_style( 'genericond', plugins_url( 'css/genericond.css', __FILE__ , '', self::$gen_ver ) );

The first one is for Genericons, the library. There I use the common name of genericons which means if anyone else also enqueues Genericons with this name, one of ours will win depending on load order. For my personal plugin CSS, I use the name genericond (notice that D?) as it matches the name of my plugin and, therefore, is less likely to conflict with someone else’s plugin.

Conflict is the name of the game here. I actually want genericons to conflict. Well, not conflict. I want it to be recognized as a shared library, so WordPress only loads it once. If I had named it genericond-genericons then, in the event someone has Jetpack or a theme like TwentyFifteen which both include Genericons, they would load the entire library twice! And I would suck. On the other hand, if we all share the library name, WordPress will check, see it’s loaded, and carry on.

Name what’s yours in a way unique to your plugin or theme.

Name what’s shared in a way that’s unique, but also stupid obvious and easy to share.

Font-Awesome? Use font-awesome for your enqueues.

As for functions and class names, even if you put in a check for ‘if this doesn’t exist…’ the logic works the same. If it’s yours and yours alone and only exists in this code, name it unique to your plugin/theme. If it’s a shared library, like the aws-sdk, name the class in the standard way and wrap it in an ‘if this doesn’t already exist…’ so that if it does exist, it only gets called once.

Standard names for shared libraries.

Unique names for your personal codes.

And bonus! If you keep your names to a standard, while being unique, someone may call your functions too.

By the way, anything global like DEFINE( 'FOO', true ); should always be unique. Those are globals. Everyone uses them. I’ve made that mistake too.