Apex CodeThe following is a primer on default namespaces in every org and how they are used in Apex.

First, here’s a fun “trick” you can play on yourself!

Step 1

Run this snippet in the execute anonymous window:

sObject[] acct = Database.query(‘Select id, Name from Account Limit 1’);
system.debug(acct[0].get('name'));

Step 2

Create this class in your org:

    public class Database {
        public static String query() {
            return 'wherefore art thou namespace?';
        }
    }

Step 3

Run the same snippet from Step 1 again.

This time you get an error – method does not exist or incorrect signature. What happened? To illustrate, let’s try one more step.

Step 4

Run this modified snippet:

sObject[] acct = System.Database.query(‘Select id, Name from Account Limit 1’);
system.debug(acct[0].get('name'));

Notice the slight difference? In this last step, we’re explicitly referencing the System namespace, which we typically don’t need to do. By making this minor change, we again get access to the query method as we expect.

What is at play here is that Apex offers you two “default” namespaces. Your org gets an implicit namespace, and the System namespace is provided to all orgs. By “default”, I mean you do not need to explicitly identify these namespaces when making a function call. In this example, the two namespaces are colliding, in that we have a “Database” class in each.

Every org has its own org namespace, which is where all of your custom Apex classes live. You don’t need to know the actual name for your org’s namespace unless you are going to do packaging and distribution, so you can just pretend it has no name at all. You can conveniently refer to any custom classes directly, without any prefix:

//this
MyClass m = new MyClass();
//not this
//MyOrgNamespace.MyClass m = new MyOrgNamespace.MyClass();

Apex also provides the System namespace to all orgs, which is where all of the standard features live. This includes things like the Math methods, the HTTPRequest class, the Test methods, and the Database methods. Since these are common to all orgs, you are not required to prefix your calls to things in the System namespace with “System.”, but you can explicitly do so whenever you feel like enhancing the readability of your code. This is also intended to be more convenient for the programmer … think of it like automatically having an “import System.*” statement in every Apex context.

You have quite possibly never been aware of these namespaces, since there is rarely any interaction between them. Until I told you to play a trick on yourself in this post, you probably wouldn’t have thought to name a class “Database”. Thus, when there is a conflict, like in the example here, you could end up confused.

Your Org’s Namespace has Priority Over the System Namespace

In this example, the compiler first looks to see if your org has a “Database” class, and if so, it uses that. The compiler next looks in the System namespace for a “Database” class. Thus, you can accidentally (or intentionally) override a System namespace class!

You can use a class in both your own namespace and the system namespace in the same org. By explicitly using the “System.” prefix, you tell the compiler that you’re looking for the functionality in the System namespace, rather than your custom class. This allows you to create a class named “Database” for your own purposes, while still having access to the System.Database methods. Your own class is accessed without prefix, and the System class is explicitly referenced:

Database d = new Database();  //your class, without prefix
System.debug(d.query());  //'wherefore art thou namespace?'
sObject[] accts = System.Database.query('Select id, Name from Account');  //explicit prefix, queries using the system database method

I have encountered several situations where a developer created a class named “Test”, unaware they would block the system Test methods (e.g. Test.startTest()). As you can imagine, this has created some confusion for some unsuspecting programmers when they went to run tests!  This could be solved by renaming the custom Test class, or by calling System.Test.startTest() across the org.

 

Now you know more, and you are a stronger developer.  Happy Coding!

tagged , Bookmark the permalink. Trackbacks are closed, but you can post a comment.
  • Abhinav Gupta

    I learned this in hardway, some utility class by name “Test” messes up the real Test for similar errors :)

    • Varun Chaddha

      been there … done that ;-)

    • http://twitter.com/zachelrath Zach McElrath

      It gets worse — you can also run into System errors if you name your classes the same as internal Java classes. For instance, I was building a library of CRON scheduling utilities for Apex (since one doesn’t exist), and named a class ‘CronExpression’. Turns out that is an internal Java class used by SFDC, and therefore every now and then internal System errors would be thrown when I’d compile the class. Yikes! SFDC support’s answer was to name my class something else… well, you live and learn. Always prefixing your class with your First Name usually helps :)

      • Josh Kaplan

        Java class names should not interfere with class names in your org namespace. I’m able to create a CronExpression class without any issues, so I am curious what is causing your system errors. Did you file a case on this at any point in time?

      • Abhinav Gupta

        haha this is interesting @twitter-214081828:disqus, such collisions are more deadly ;)

  • http://twitter.com/Kwongerific Brian Kwong

    What would happen if a developer has a name space that later ends up as a system namespace? For example before Test.StartTest() existed a Dev name of “test” would’ve been fine.

    • Josh Kaplan

      The behavior would be the same as described here. Your code would continue to work, and your org would not have implicit access to the new System class. You would need to explicitly use the “System.” prefix for the new system class.

  • http://twitter.com/alex_berg Alex Berg

    Great info! I’ve often wondered how namespaces are used in Salesforce.

    Bit of a side-thought, but I’d like to see a similarly technical blog post on managed packages. How do managed packages work behind the scenes? As I understand it, the package namespace must be used when referencing its classes and methods. Why is that? Are these classes residing in the org’s database, so to speak, or are they remotely referenced? Their code isn’t visible, and logs are handled a bit differently, which makes them feel like they reside in another system somewhere.

    • http://twitter.com/zachelrath Zach McElrath

      Alex, great idea on a good solid blog post on best practices for building Managed Packages. The Package Namespace does NOT need to be used WITHIN the DE org used to build the package — only in code/packages extending the base package. For instance, if in the DE org for my Managed Package with namespace ‘acme’, I’m writing a trigger on an object that’s included in that package called “Widget__c”, I can always refer to that object without the namespace, e.g.

      trigger Widgets on Widget__c(before insert) {
      for (Widget__c w : Trigger.new) {
      w.MyField__c = ‘blah’;
      }
      }
      And this, in my experience, is best practice, because (1) it increases portability of your code (2) decreases amount of code you have to write (esp if your namespace is more than 3 characters)
      However, this gets complicated when you get out of Apex and Visualforce and start working, say, with JavaScript Remoting. Once your package is Managed, you’ll always have to start referring to its objects and fields with the namespace prefix, e.g.
      var widgets = result.acme__Widgets__r;$.each(widgets,function(i,widget){widget.acme__Widget_Size__c += 2;});
      But better yet, this should all be described in more detail in a blog post :)

  • http://www.facebook.com/adam.purkiss1 Adam Purkiss

    Great post! I’ve often wondered if calling out the System namespace was a good idea, or if it just cluttered code unnecessarily. Now I’m always going to prefix System classes/methods with System.[class/method].

  • Chirag Mehta

    Great post, and really nice clarification.

  • niket soral

    Great post. I knew about the collision but never thought in deep like this. Thanks for it.