Header documentation.gif

Download PDF‎.

As an on demand platform, Apex provides a complete set of features for building business applications – including data models and objects to manage data, a workflow engine for managing collaboration of that data between users, a user interface model to handle forms and other interactions, and a SOAP API for programmatic access and integration. (For more information on the core capabilities of the Force.com platform, see Creating Applications with the Force.com Platform). These Force.com platform technologies have been a core part of every Salesforce deployment for several years now, supporting thousands of custom applications and integrations, and allowing thousands of developers to experience the benefits of building with this on demand model.

New to this platform is Apex Code – the world’s first on-demand programming language. Apex Code extends the powerful and proven success of the Force.com platform by introducing the ability to write code that runs on salesforce.com servers. The language enables a new class of applications and features to be developed and deployed entirely on demand. These applications make existing Force.com apps “smarter” by providing the ability to capture business logic and rules – such as data validation – and make entirely new kinds of apps possible on demand – such as complex inventory checking and order fulfillment.

Among the concepts behind Apex Code, two provide an especially good introduction to the language’s potential and implementation.

Multi-tenancy and Programming Languages

Like all aspects of salesforce.com’s application and platform technologies, Apex Code is “on demand,” running entirely on Force.com without requiring any local servers or software. And as with those other technologies, the language runs in a multi-tenant environment, providing the economic and manageability benefits of a shared service while keeping the definition, data and behavior of each customer’s application entirely separate from each other. For developers, the combination of Apex Code’s capabilities with this on-demand, multi-tenant delivery provides the best of two worlds: the convenience, scalability, and safety of an on-demand database, combined with the flexibility and control of a procedural language. In other words, Apex Code lets developers and IT organizations focus on innovation, not infrastructure.

Diagram apexcode multitenant.jpg

This combination of multi-tenancy and procedural programming is what makes Apex Code unique, both in its design and implementation. Hence design considerations about where and how to use Apex Code differ from languages like C++, Java and .NET. Unlike those languages, Apex Code is much more limited in scope; whereas a language and platform like Java can be used to build almost any kind of application – from a video game to a vending machine – Apex is exclusively for building business applications to manage data and processes within the larger context of the Force.com platform framework. But within the scope of business applications, Apex Code provides a uniquely powerful and productive approach to creating functionality and logic, allowing developers to focus just on the elements specific to their application, while leaving the rest of the “plumbing” to the platform’s framework. And where languages like Java and C++ execute at a low level, utilizing as many and as much system resources as the underlying hardware can support, Apex Code is abstracted and governed, utilizing only as many resources as is allowed.

This “governor” is essential, as until now, multi-tenancy has been associated strictly with data: a multi-tenant database allows data operations for one “tenant” to be completely isolated from the other tenants. But those operations have not included complex business logic, because even a few ill-considered lines of code can create a resource-consuming “monster” that can potentially impact all applications and the people using them. If a piece of code goes into an infinite loop or wants to fetch a billion records, the rest of the system can grind to a halt. The breakthrough for Apex Code is that it isolates and contains such behavior.

The technology breakthrough came in the form of an additional layer of abstraction: a sort of “virtual, virtual machine” that governs the executing of a given component of Apex Code. This layer of abstraction is a remarkable achievement – enabling the first business programming language that runs in a multi-tenant environment. This multi-tenant virtual machine monitors the code execution, including the total number of data queries issued, the amount of data retrieved, the number of data operations and transactions performed, and the number of control structures like loops that are executed. By constraining and monitoring the code at all times, the Apex “virtual virtual machine” enables the flexibility and power of a programming language while providing the safety and control required for multi-tenancy.

Apex Code Design and Syntax

Apex Code is designed explicitly for expressing business logic and manipulating data, rather than generically supporting other programming tasks such as user interfaces and interaction. Apex Code is therefore conceptually closer to the stored procedure languages common in traditional database environments, such as PL/SQL and Transact-SQL. But unlike those languages, which due to their heritage can be terse and difficult to use, Apex Code uses a Java-like syntax, making it straightforward for most developers to understand. And like Java, Apex Code is strongly typed, meaning that the code is compiled by the developer before it is executed, and that variables must be associated with specific object types during this compile process. Control structures are also Java-like, with for/while loops and iterators borrowing that syntax directly.

Because Apex Code is a process and data language, developers will primarily interact with APIs to query, manipulate and save information in their custom and standard objects. Developers can select data using the existing Salesforce Object Query Language (SOQL) syntax already found in the existing Web services API, as well as a new addition to that syntax that can retrieve information from multiple objects via a single query. In general, interacting with the Web service API via a language like Java is very similar to the experience of interacting with the data APIs in Apex Code.

Apex Code Example

This simple Apex Code example illustrates both the language syntax and how it can be used. The code defines a trigger that prevents duplicate records, using email address, from being entered into the system.

trigger blockDuplicates_tgr on Lead bulk(before insert, before update) {
       * begin by building a map which stores the (unique) list of leads 
       * being inserted/updated, using email address as the key. 
      Map<String, Lead> leadMap = new Map<String, Lead>();
      for (Lead lead : System.Trigger.new) {	            
            if (lead.Email != null) { // skip null emails
            	/* for inserts OR  
            	 * updates where the email address is changing 
            	 * check to see if the email is a duplicate of another in 
            	 * this batch, if unique, add this lead to the leadMap
            	if  ( System.Trigger.isInsert || 
            		  (System.Trigger.isUpdate && 
                      	lead.Email != System.Trigger.oldMap.get(lead.Id).Email)) { 
	                  if (leadMap.containsKey(lead.Email)) {
	                        lead.Email.addError('Another new lead has the same email address.');
	                  } else {
	                        leadMap.put(lead.Email, lead);
      /* Using the lead map, make a single database query, 
       * find all the leads in the database that have the same email address as 
       * any of the leads being inserted/updated.
      for (Lead lead : [select Email from Lead where Email IN :leadMap.KeySet()]) {
            Lead newLead = leadMap.get(lead.Email);
            newLead.Email.addError('A lead with this email address already exists.');

In this example, you can see some key concepts at work: the Java-like syntax of the variable declaration and if statement, the use of SOQL to retrieve data just as one would with the SOAP API, and the use of the trigger declaration to define the trigger’s scope, that is, what events it acts upon.

In addition, no Apex Code trigger would be complete without test coverage, this is done using a class with a special testing method, the test code does not commit records to the database and so can be run over and over without modifying your database. Here is a sample test method to verify the above code works.

public class testBlockDuplicatesLeadTrigger {
	static testMethod void testDuplicateTrigger(){  
		Lead[] l1 =new Lead[]{
			new Lead(  Email='homer@fox.tv', LastName='Simpson', Company='fox' )
		insert l1;		// add a known lead
		Lead[] l2 =new Lead[]{
			new Lead(  Email='homer@fox.tv', LastName='Simpson', Company='fox' )
		// try to add a matching lead
		try {	insert l2;	} catch ( System.DmlException e) { 
			system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
		// test duplicates in the same batch
		Lead[] l3 =new Lead[]{
			new Lead(  Email='marge@fox.tv', LastName='Simpson', Company='fox' ),
			new Lead(  Email='marge@fox.tv', LastName='Simpson', Company='fox' )
		try { insert l3;	} catch ( System.DmlException e) { 
			system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Another new lead has the same email'),
		// test update also
		Lead[] lup = new Lead[]{
			new Lead(  Email='marge@fox.tv',  LastName='Simpson', Company='fox' )
		insert lup;
		Lead marge = [ select id,Email from lead where Email = 'marge@fox.tv' limit 1];
		marge.Email = 'homer@fox.tv'; 
		try { update marge; } catch ( System.DmlException e) { 
			system.assert(e.getMessage().contains('irst error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),

Apex Features and Functionality

In addition to the essential capabilities of running on demand in a multi-tenant environment, Apex Code brings a number of other features that greatly expand the power developers have in using the Force.com platform and in the range of applications they can build.

Apex Code and event model. Apex Code can be tied to the execution of the platform, enabling developers to exert fine-grain control over an application. When thinking about the Apex code, it’s useful to consider the analogy of stored procedures and triggers, since fundamentally the language is tied to behaviors on the data, as opposed to providing a higher level UI language or representation. Hence developers can tie Apex Code into almost every aspect of an application’s behavior: overriding the behavior in existing buttons, creating a new button, manipulating the control of a custom link, programming the control of an inline s-control, or even overriding the behaviors associated with a related list and data.

Consider an app that enables the user to create a new lead in Force.com by clicking the save button to commit that record to the database. With Apex code, developers can create and execute code residing on salesforce.com’s server to intercede just after the button is clicked. The code might check for any duplicate records, and if it finds any, implement a data quality scenario that notifies the user. Otherwise, the record commits to the database as is normally the case. (See Apex Code Example above.)

Transaction control. Because Apex Code is closely bound to Force.com data, developers can readily add transactional features to their applications. For example, if one user is referencing a field while somebody else is trying to delete it, the system is aware of the conflict. Apex Code also features data commits and rollbacks, which are especially important when working across multiple objects.

Packaging, re-use and Web services. Apex Code uses a packaging model similar to that of Java, in which reusable packages of code can be invoked from each other or from within triggers. Unlike Java, however, Apex is not object oriented in the sense that those packages can be modified through inheritance. Significantly, any method defined in a package can optionally be automatically exposed as a Web service, and thus can be invoked via the SOAP API or directly through the AJAX toolkit.

Performance, scalability and upgrades. Because Apex Code runs on demand, scalability, compatibility and maintenance issues are salesforce.com’s responsibility, not yours. Apex-developed applications can scale indefinitely to support additional users, without your having to deploy additional servers. Applications potentially run faster because a single query can obtain information from multiple objects.

When newer versions of Force.com and the Apex code itself are introduced, your code is never rendered obsolete. Force.com ensures backward compatibility by maintaining processor-specific versions of Apex virtual machines, which in turn correspond to the API. As a result, your code continues to operate without modification.

Apex Code and the AppExchange. Apex Code can be packaged along side custom objects, S-controls and other platform features, allowing developers to redistribute their Apex Code-enhanced apps via the same AppExchange directory available today.

Online Force.com Developer Resources

Force.com has a complete developer site available at http://developer.force.com with resources that help developers quickly create successful applications for the Force.com platform. The site includes links to online demos, presentations, documentation and code samples showing how Apex Code works in a variety of app development scenarios. Developers can also sign up for a free Developer Edition at their site to begin developing their on demand apps today .