Learning Apex Programming

4.3 (3 reviews total)
By Matt Kaufman , Michael Wicherski
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Apex Assumptions and Comparisons

About this book

Starting with the syntax and common use cases for developing in Salesforce, this book will teach you how to create and deploy applications on the fly. You will learn how to approach new projects and learn the basics of Apex, including how to use Eclipse and the sandbox.

Salesforce limits and batch processes are explained in an easy-to-understand format, and you will gain a deep understanding of triggers, classes, test coverage, and Visualforce pages. You will also discover how you can share your Force.com data and code with the outside world and how to integrate with Google calendar using Apex.

Finally, the book covers the creation of real-world web service integrations with Salesforce.com; you will create a Force.com application from start to finish using Apex as the business logic. By the end of this book, you will know all the best practices for development using Apex.

Publication date:
January 2015
Publisher
Packt
Pages
302
ISBN
9781782173977

 

Chapter 1. Apex Assumptions and Comparisons

Salesforce is the enterprise cloud computing leader. Its Customer Relationship Management (CRM) applications were designed from the ground up to use a Software as a Service (SaaS) model. Their success revolutionized the technology sector and changed the way software is delivered. Powering their applications is the Salesforce1 Platform, which is a highly scalable, multitenant Platform as a Service (PaaS). This platform is not just for salesforce.com's applications but is available to anyone to build a custom SaaS application. The programming language used on the Salesforce1 Platform is called Apex, and this book will get you started developing with it.

Apex isn't your typical programming language, so this isn't your typical programming book. We assume you already have experience with some other object-oriented programming language and aren't interested in reading about the basic concepts again. Instead, we take a more practical approach and explain what you need to know to start coding right away. We don't waste your time with Hello World code samples, and instead we walk you through writing fully functional code that is useful and serves business purposes.

 

Before you start


Apex is a proprietary language that can only be compiled and executed by the Salesforce1 Platform. The Salesforce1 Platform is not open source and only runs on servers owned by the salesforce.com company. For these reasons, the purpose of Apex is to extend the Salesforce1 Platform beyond its native features. This might be the most important lesson in this book and can be summarized by two simple rules:

  • Leverage built-in features: Don't waste your time writing Apex code to do things that the Salesforce1 Platform can already natively do. Built in to the platform are robust features for authentication, reporting, workflow, and more. A good Apex developer is familiar with these features and works with them. Not only will this simplify your development process but also enable system administrators to manage items that frequently change. It will also ensure your projects are future compatible with the long list of feature enhancements salesforce.com delivers with each release.

  • Calculate your ROI upfront: the Salesforce1 Platform uses a per user subscription model. Before you start developing, determine the costs and benefits of the project. When enhancing an existing application, you should always look for some type of commonality between your existing application and your new one, either in data, users, or administration. A commonality of data might facilitate greater accuracy and better reporting. A commonality of users will reduce costs and improve adoption. A commonality in administration will also reduce costs and hopefully development time. If this is your first use of the Salesforce1 Platform or there are no overlaps, then evaluate the development time, which tends to be much lesser on the Salesforce1 Platform.

These might seem like trivial points, but in our experience working on over 500 projects on the Salesforce1 Platform, the long-term success of any project relies on them.

 

A gift to our readers


The Salesforce1 Platform is a commercially available service that requires a paid subscription. You might already be a customer of salesforce.com and have access to the platform, but it's OK if you don't. Either way, as a loyal reader of our book, we want to show you how you can register for a free Developer Edition and start coding right away. Don't worry, there's no catch; it's perfectly legitimate. In fact, salesforce.com not only allows anyone to register for a free Developer Edition of its service but actually encourages it. Simply visit developer.salesforce.com and click on the JOIN NOW button in the top-right corner. Within seconds of registering, you'll receive an e-mail with a link to log in and set your password. Be sure to remember your username and password as you'll need them later in the chapter.

Tip

A company that gives away its paid service would not last long; that's why the Developer Edition is built with limits that make it perfect for writing code and experimenting, but not actually running a business. This usage restriction is also spelled out in the fine print, so don't get any ideas.

The Salesforce1 Platform has over 100,000 subscribing businesses with millions of users logging in each day. A subscription can be for as few as one user license or as many as you want. When you log in to the Salesforce1 Platform, your unique username and password are used to identify you and the subscribing organization you are a part of. All of the data, schema, and code specific to your organization are available to other users at your organization but are private for everyone else. The collective term for your unique instance of the Salesforce1 Platform is commonly known as your org. In later chapters, we'll discuss the various ways you can share your code outside of your org. For now, take comfort in knowing that the code in your Developer org is secure and won't be seen by anyone else.

 

Safety first


Before we go any further, let's talk about safety. Safety is certainly not a normal topic when discussing a programming language, but like we said, Apex is unlike any other language. Apex is intrinsically tied to the Salesforce1 Platform, a platform which businesses use to run their operations and track critical pieces of data. Apex is extremely powerful, and we all know what comes with great power. With this in mind, we want to make sure that while this book might teach you enough to be dangerous, you will pose no danger to anyone.

Writing code directly to an in-use Production environment is not a good idea. At best, you might inconvenience and annoy some users. At worst, you might make an error that brings your company to a standstill. It is for this reason that all paying customers of salesforce.com receive an included Sandbox environment. This Sandbox is an exact copy of your Production org's configuration, code, and other metadata. If you have a complex development process or multiple developers, you can purchase additional sandboxes with your subscription. You can even purchase a Full Sandbox, which not only includes your metadata but also all your data.

To ensure that your code is not destructive, the Salesforce1 Platform does not permit Apex code to be written directly to a paying subscriber's Production org. This means that you must write your code to a Sandbox org or a Developer Edition org. In later chapters, we will discuss the requirements, process, and tools to deploy your code to a Production environment. If you skipped the previous page, go back and sign up for a free Developer Edition of the Salesforce1 Platform. Now, buckle up because we're about to get technical!

 

The Force.com IDE


The Salesforce1 Platform's GUI includes its own web-based code editor. You can use this tool while on the Web to write Apex code. However, for serious development, programmers turn to a robust Integrated Development Environment (IDE). The Force.com IDE is a software-based tool provided by salesforce.com that is designed to interact directly with Salesforce1 Platform. It includes the ability to read, write, and execute code directly on the server. It can store your credentials, which makes it faster to log in. It can even help you build and run queries against the database. Frankly speaking, the Force.com IDE makes it easier to develop applications for the Salesforce1 Platform, so we will show you how to install and use it.

The Force.com IDE isn't something you just install. It actually consists of three parts that build on top of each other, so you can't skip any of them:

  • Java Runtime Environment (JRE): This is the backbone for any Java-based program you want to run on your computer.

  • The Eclipse IDE: This open source integrated development environment is widely used by developers of different programming languages. It supports code completion, syntax highlighting, version tracking, and more.

  • Force.com IDE plugin for Eclipse: This plugin extends Eclipse from just editing files on your local computer to being able to connect directly to the Salesforce1 Platform.

Installing the Force.com IDE and its prerequisites can sometimes be frustrating. The simplest path is to follow the latest instructions provided at https://developer.salesforce.com/ or to search for Force.com IDE Installation with your favorite search engine. These downloads are relatively large (around 200 MB total), so make sure that you have enough bandwidth and time.

To start, you will need to install the Java platform, Standard Edition Runtime Environment (JRE), for desktops (not servers). The JRE is the backbone for any Java application you want to run on your computer (such as Eclipse). At the time of writing this book, the JRE is owned and maintained by Oracle and can be found on their website. It is available for free under Oracle Binary Code License and does not require you to register to download. This software is supported on Linux, Mac OS, and Windows and comes in 32- and 64-bit versions. Either version is fine; however, you do need to match the bit version of the JRE with that of Eclipse. After downloading, install the software and reboot if needed. If you already have the Java Development Kit installed, then you should be able to skip this step.

Downloading Java SE Runtime Environment (JRE)

Once you have the JRE installed, it's time to download and install Eclipse. Eclipse is an open source development platform that has existed for over a decade, and it is independent from salesforce.com. It runs on Linux, Mac OS, and Windows (in alphabetical order) and is community driven. It is highly popular among developers and the IDE of choice for Software Development Kit of many other web-based services. There are many packages of Eclipse for different purposes and even some that are branded by various companies. You might want to download the Eclipse IDE for Java Developers; it includes all the prerequisite plugins and some additional ones that you might want to take advantage of. Even if you already have Eclipse installed for some other work, it's a good idea to download a new copy that you will use just for development on the Salesforce1 Platform. Again, be sure to download the version that matches the bit size of the previously downloaded JRE.

Tip

Eclipse takes up a lot of disk space and uses a lot of memory, so if you're low on either, you can install the Eclipse Platform Runtime Binary package for a minimal install. You might need to add some missing plugins to use the Force.com IDE or take advantage of some of the features that we will discuss later.

Eclipse does not have an installer. Instead, you just uncompress the downloaded file and move the resulting folder to the appropriate location on your hard drive. Inside the folder, there will be an executable named Eclipse, which you use to run the program.

Downloading the Eclipse IDE for Java developers

When you first start Eclipse, you will be prompted to select a workspace. A workspace is a folder on your hard drive where you will store all of the files pertaining to projects you work on. You can create multiple workspaces and change their locations at anytime. So for now, just accept the default location and click on OK to proceed. The first time you use Eclipse, you'll be presented with the welcome screen that includes options to view and overview samples, tutorials, and more. These are great resources if you haven't used Eclipse before. When you're ready, you can click the link to go to Workbench. You can always return to the welcome screen from the Help menu.

Now that Eclipse is up and running, it's time to install the Force.com IDE plugin. Eclipse has a nice built-in tool that makes it easy to download, install, and update plugins from the Web. All you need to do is provide the URL from where the plugin is hosted and Eclipse will take care of the rest. The URL for the Force.com IDE can be found in the installation instructions at http://developer.salesforce.com. To install the Force.com IDE from Eclipse, perform the following steps:

  1. Click on the Help menu and then select Install New Software….

  2. Click on the Add button to add a new repository.

  3. Enter Force.com as the name.

  4. Paste the URL http://media.developerforce.com/force-ide/eclipse42, and then click on OK.

    Eclipse will automatically start the process to download and install the software.

    Adding the Force.com repository to Eclipse

  5. Check the box to select Force.com IDE and click on the Next button.

    Eclipse will automatically determine whether there are any other packages required and display a list of everything that will be installed.

  6. Click on Next again to review the licenses for everything being installed.

  7. Select the radio button to accept the licenses and click on Finish.

    Depending on your Internet connection, this can take a while.

  8. When done, you'll be prompted to restart Eclipse; click on Yes.

Take a deep breath; the hard part is over.

 

Getting comfortable with Eclipse


You finally have the Force.com IDE installed, but there's a few more steps you need to take. It probably doesn't look like Eclipse has changed much, so let's fix that by performing the following steps:

  1. Click on the Window menu and navigate to Open Perspective | Other. A list of available perspectives will appear.

  2. Select the Force.com option and then click on OK.

    The layout of Eclipse should change slightly and also now display Force.com Start Page; you're finally home!

    The Force.com perspective in Eclipse

Eclipse is highly customizable and has a long list of settings available from the Preferences menu available in the Window menu (the Eclipse menu on Mac). Before we get underway writing code, here are a few tweaks that we recommend you follow, which will help you have a better coding experience:

  • Show line numbers: This is an absolute must! Navigate to General | Editors | Text Editors and check the Show line numbers box.

  • Set default perspective: Ensure that Eclipse always starts out in the Force.com perspective. For this, navigate to General | Perspectives, select Force.com, and click on the Make Default button.

  • Colors and fonts: You might want to make things easier on the eyes. To do so, navigate to General | Appearance | Colors and Fonts.

  • Web browser: Everyone has a personal preference, but you might want to specify an alternate browser when opening web pages from Eclipse. To set this, navigate to General | Web Browser and select your browser.

In addition to these preferences, we also recommend moving the Outline view under Package Explorer. You can do so just by dragging it to the bottom half of Package Explorer. This will increase the size of the editor and make it easier to see more of your code.

If you're like us, you wouldn't like to type things over and over again. Eclipse comes with a Snippets feature that lets you save frequently used code blocks and then use them just by double-clicking on them. You can even use Merge Fields to represent variables that you specify upon use. To get started with your first Snippet, perform the following steps:

  1. Navigate to Window | Show View | Other….

  2. Type in Snippets in the filter box.

  3. Select the Snippets option and click on OK. The Snippets panel appears in the bottom portion of Workbench.

  4. Right-click on the Snippets panel and select Customize…. The Customize Palette window appears.

  5. Click on the New button and select New Category.

  6. Change the name of your new category to Apex and click on Apply.

  7. Right-click on the Apex category in the list and navigate to New | New Item.

  8. Click on the new Unnamed Template item.

  9. Change the name of your new item to System Debug.

  10. Change Description to Outputs to Debug Log.

  11. Click on the New button to create a new variable.

  12. Click on the new variable name and change it to Variable.

  13. Set Description to Variable Name or String.

  14. Type String in Default Value.

  15. Type the following line of code in the template:

    system.debug(${Variable});
  16. Click on Apply and then OK.

You just created your first Snippet. You can't use it just yet but go ahead and put a sticky on this page so that you can come back later and create more Snippets with useful code. In later chapters, when we are writing code, we'll use this Snippet.

Creating your first Snippet in Eclipse

 

Linking Eclipse to the Salesforce1 Platform


Before you can write any code, you'll need to set up a new project in Eclipse. You'll need your Sandbox or Developer Edition org credentials to do this. If you don't have either, go back to our earlier section on how to register for a free Developer Edition.

When you log in to the Salesforce1 Platform via your web browser, you use a username and password and use e-mail or SMS for two-factor authentication. When you log in programmatically via a tool (such as Eclipse) that leverages the Salesforce1 Platform's APIs, you need a third credential called a security token. This security token is generated by the platform for each user and is automatically reset anytime a password is changed. To obtain your security token, you will need to first log in to the Salesforce1 Platform via your web browser. Once logged in, you can click on the drop-down menu at the top of the window labeled with your full name. Select the My Settings option and then expand the Personal section on the left. Click the Reset My Security Token link to read more about how the security token works, and then click the Reset Security Token button. Your security token will be generated and e-mailed to you. We recommend starring this e-mail to make it easy to find later.

Tip

Instead of using a security token, you can whitelist your IP range from Setup | Administer | Security Controls | Network Access. Doing so will simplify the login process while you are in the IP range, but make it more complicated when you are not. Check with your IT policies prior to whitelisting any IPs and always make sure that they are static and will not change.

Now that you have your username, password, and security token, you can create a new project in Eclipse. Navigate to File | New | Force.com Project and a New Force.com Project window will appear. Give your project a name. We recommend including a date in the name as well. This will allow you to create multiple projects for the same org over time; this is a low-tech way of backing up your code right inside Eclipse. Enter your username, password, and security token. If you are using a Developer Edition, keep the Environment as Production/Developer Edition. If you are using a Sandbox, change it to Sandbox. When complete, click on the Next button to have Eclipse authenticate and retrieve a list of your existing metadata.

Entering your Force.com credentials in Eclipse

After authenticating, you will be prompted to select which metadata you want to download into Eclipse. The default option is only Apex and Visualforce, which is perfect for the purposes of this book. You can also select from all possible metadata components or choose to work with a blank slate by selecting the None option. Click on the Finish button to have Eclipse download your metadata into text files in your workspace organized into folders by type. You're ready to start coding, so let's take a more in-depth look at the Salesforce1 Platform and its Apex programming language.

 

Under the hood


You definitely don't need to understand how the Salesforce1 Platform works in order to write Apex code. You might find it interesting though, and it might answer some of your questions about Apex's behavior. For several years, salesforce.com has been called the most innovative company in the world. While its growing number of customers might be the interest of financial analysts, in our opinion, the real innovation is behind the scenes with Apex. Apex was the first multitenant, on-demand programming language. It is compiled and executed Just In Time (JIT) by Force.com platform servers.

The Salesforce1 Platform is designed to scale, so multiple threads of your code won't impact performance. In fact, roughly 50 percent of all transactions on the Salesforce1 Platform are programmatic and not performed via a Graphical User Interface (GUI). It has taken years for the other major players on the Web to start developing their own programming languages, and it's no surprise that they have a striking resemblance to Apex. Despite being proprietary, Apex continues to be at the forefront of web development and evolves at a very rapid pace. salesforce.com produces three major releases each year while still maintaining backward compatibility for previous versions. These releases include community-driven features and typically simplify the development process.

Apex is a class-based object-oriented programming (OOP) language originally modeled after Java. It is often referred to as being Java-like, and at first glance, you might even think that it is Java. However, since its original design, concepts and methods of other programming languages have been incorporated into Apex, making it easier for non-Java programmers to adopt it. Regardless of your programming language of choice, Apex is the only language for you to choose if you want to run code on the Salesforce1 Platform.

The Salesforce1 Platform is powered by a myriad of technologies, but its core is Java. However, Apex code is not compiled into Java; it's actually stored as a series of instructions in metadata. This metadata also includes any nonprogrammatic configuration changes or customizations made via the Salesforce1 Platform's GUI. One of the biggest selling points of the Salesforce1 Platform is the ease in which a nonprogrammer can make declarative changes to the behavior and design of the application. While this was a true game changer in the industry, the more astounding feature is that custom instructions compiled from your code are executed along with (as opposed to after) the standard ones. Essentially, the Salesforce1 Platform considers your code to be just as important as the core code that powers built-in functionality.

The primitives we use in Apex are not Java primitives. The smallest unit of processing in Apex is an object. This primitive is the most generic data type in Apex and all other data types (including tables defined via the GUI) are inherited from it. The following is a list of Apex primitives, each of which has their own characteristics and methods. For a complete list of their methods, refer to the Force.com Apex Code Developer's Guide located at http://developer.salesforce.com.

  • Blob: This is a single object that consists of a collection of binary data. These are commonly used for file bodies and with web services.

  • Boolean: Unlike other languages, an Apex Boolean is null unless set to true or false.

  • Date: These are typically constructed using a static method on the built-in Date class. Apex Date does not include time (see DateTime). They also cannot be used with arithmetic, but have methods to facilitate such operations.

  • DateTime: These are typically constructed using a static method on the built-in DateTime class. Apex DateTime cannot be used with arithmetic, but have methods to facilitate such operations.

  • Decimal: This is the most commonly used number data type; it includes a decimal point and represents any number fields created via the GUI.

  • Double: This is a 64-bit number that includes a decimal point. (It is a large Decimal value.)

  • ID: This is an 18-character string only set by the platform that is used to uniquely identify a record in the database.

  • Integer: This is a positive or negative whole number (without a decimal point).

  • Long: This is a 64-bit number that does not include a decimal point. (This is a large Integer value.)

  • Object: This is the smallest unit of processing from which all other data types are inherited. (It is a singularity from which all of Apex is derived!)

  • String: Any characters found between two single quotes.

  • Time: This is typically constructed using a static method on the built-in Time class. Apex Time does not include dates (see DateTime). They also cannot be used with arithmetic, but have methods to facilitate such operations.

All statements in Apex must end with a semicolon. Apex as well as queries against the database are not case sensitive. Apex is statically typed, which means you must specify the data type for a variable before using it. Apex is also described as being strongly typed; however, it does include methods that return a value as an alternate data type and supports casting. While some other languages might be more flexible, these rules do ensure accurate interpretation by the platform (and your colleagues). There are methods to convert variables from one data type to another, and you can cast variables to another data type as well. When declaring variables, you do so with syntax similar to Java demonstrated as follows. However, note that the initial value of a variable is null unless otherwise specified:

String stringExample = '10'; //Looks like a number but is a string
Integer integerExample = integer.valueOf(stringExample);
system.assert(integerExample == 10);
Date d = date.newInstance(2014,1,1); //Happy New Year
Time t = time.newInstance(0,0,0,0); //Midnight
DateTime dt = dateTime.newInstance(d,t);
Boolean nullBoolean;
nullBoolean = false;

In this code sample, we construct a String variable that consists of the numbers 1 and 0 (also known as the number 10). We then construct an Integer variable from that string using the valueOf() method on the built-in Integer class. We then prove that the integerExample variable really is the integer 10 using the system.assert() method. Next, we construct the Date, Time, and DateTime variables using the newInstance method on their respective built-in classes. These methods are overloading and available with different input parameters. Next, we construct a Boolean variable without setting its value, and then we set the value of Boolean from null to false.

To ensure that your code performs efficiently and does not exceed the platform's limits, Apex heavily relies on collections. Collections are one or more objects grouped into a single unit. Collections can hold any data type including primitives, classes, and even collections. In fact, collections can be nested inside other collections up to five levels. As we'll see later in the book, it's a best practice to always group your objects and write methods that operate on these groups. Apex includes three types of collections, each with their own unique methods:

  • List: This is the most common collection data type. It can be declared and functions very closely to an array in other languages. It includes a sort() method, so we use lists whenever we need something to be ordered.

  • Set: This automatically enforces uniqueness. We use it constantly to prevent duplicates in our code. In exchange for this super power, sets are unordered.

  • Map: This is a complex collection that consists of key-value pairs. Keys behave like a set (which is unique), while values typically behave like a list. The correlation of the two allows us to keep track of objects based on their keys rather than just their positions in a list. This is shown in the followind code:

    List<Integer> myIntegerList = new List<Integer>();
    myIntegerList.add(100);
    myIntegerList.get(0);
    
    String[] arrayLikeNotation = new String[10];
    arrayLikeNotation[0] = 'Item 0'
    system.assert(arrayLikeNotation.size() == 10);
    
    Set<Date> uniqueSetOfDates = new Set<Date>()
    uniqueSetOfDates.add( system.today() );
    uniqueSetOfDates.add( system.today() );  //This overwrites the first instance of today's date and does not result in two items being in the Set.
    Map<Date,String> dateStringMap = new Map<Date,String>();
    dateStringMap.put(system.today(),'Monday');
    dateStringMap.put(system.today(),'Tuesday');  //This overwrites the first key-value pair.
    system.assert(dateStringMap.get(system.today)=='Tuesday');
    system.assert(dateStringMap.size()==1);

This code demonstrates how to create and work with all three types of collections. For a complete list of methods unique to each type of collection, refer to Force.com Apex Code Developer's Guide located at http://developer.salesforce.com.

Primitives and collections serve as the building blocks for the majority of our Apex code. Although we don't use it as often, Apex also includes support for enums or enumerated lists. This is a special data type that you can define in your code to have specific constant values. As we'll see in later chapters, the Salesforce1 Platform uses enums internally for all sorts of things, but you can also use them to enforce your constant values.

 

Data and metadata


Since its release, one of the biggest selling points of the Salesforce1 Platform is the ease at which anyone can make configuration changes through the platform's GUI. Naturally, when Apex was first developed, a key requirement was the ability to easily interact with these objects and their data in the database. The folks at salesforce.com took an innovative approach to this and tightly coupled Apex with the metadata of the Salesforce1 Platform.

The data stored on the Salesforce1 Platform has the sObject data type. This data type can be used to refer to the generic concept of any record regardless of the object type. Each of the built-in tables and custom tables you create on the Salesforce1 Platform automatically have their own unique data type that is inherited from the generic sObject data type.

When you write Apex code, you can refer to any of the metadata on the Salesforce1 Platform. The data type of that metadata is automatically known by a compiler and the Force.com IDE. This allows you to reference sObjects and their fields without having to cast them. It also makes the IDE's code complete functionality extremely useful as it provides you with all the attributes and methods you need at the touch of your fingers.

Even more amazing is that the Salesforce1 Platform is aware of the metadata you reference in your Apex code. When you reference a sObject or field in your code, the platform automatically protects those components from destructive changes. This amazing attention to detail ensures that once your code can rely on sObject and fields as existing and being of the same data type, not just upon compilation but every time it is executed in the future. Given the ease at which someone can make changes to sObjects and fields, this is a critical feature which is shown as follows:

Account newAccount = new Account();
newAccount.Name = 'Acme';  //This is a string field
newAccount.IsCustomerPortal = true; //This is a boolean field
newAccount.AnnualRevenue = 10000000; //This is an integer field
List<sObject> myList = new List<sObject>();  //This is a List that can hold multiple sObjects regardless of table.
myList.add(newAccount);
insert myList;  //This creates a new record in the database

In this code, we first construct a new instance of an Account sObject. This is a standard sObject that is included in the Salesforce1 Platform, and it is typically used to track a company. We're able to reference all the fields on the Account table by name and the data types of those fields are automatically known by Apex. This means that it will not be possible to set the AnnualRevenue variable to a string or IsCustomerPortal to a date. Next, we constructed a list of sObjects (in this case, we could have constructed a list of Account objects and been limited to adding only objects of the Account data type). We then use the .add() method to add our newly constructed account to the list. Finally, we insert the entire list of sObjects into the database. We'll discuss all of these concepts in greater detail later, and you can always read more about the specific methods in Force.com Apex Code Developer's Guide located at http://developer.salesforce.com.

 

Writing code


If you're familiar with object-oriented programming, then it's fairly easy to start writing Apex code. The rigid structure of the language provides easy-to-follow rules to ensure that your code is valid. In fact, the compiler even prevents you from saving code that is syntactically invalid and provides easy-to-understand error messages that include line numbers. On top of this, all transactions are monitored by the platform and will be automatically terminated if an exception is thrown or a limit is exceeded. Essentially, you can write code in your Developer Edition without having to worry about breaking anything.

Irrespective of whether you are using the Force.com IDE or the web-based editor, there are only two places in the Salesforce1 Platform where you can store Apex code: triggers and classes.

Just like all of Apex, triggers are compiled into a set of instructions stored as metadata. However, what makes triggers unique is that these instructions can only be invoked by the platform itself. Each trigger is tied to the operation on records of a specific sObject type in the database. The individual operation (insert, update, and so on) for the data type can also be specified. Triggers allow you to modify the default behavior of the platform when a record is saved.

As triggers are only called by the platform, classes end up being the main stomping ground for Apex code. Classes aren't limited to being called by the platform. You can interact with them from other classes and triggers, call methods on demand from Execute Anonymous (similar to a command line editor), and even expose them outside as web services.

Classes can be instantiated just like any other object. However, as the Salesforce1 Platform is a multitenant service, we typically use a lot of static methods to avoid creating a bunch of short-lived instances. These methods can be called directly without first instantiating a class. The built-in Apex classes include a lot of static methods, and the best practice is for your code to do the same as it will use fewer resources and this reduces the chances of hitting the platform limits. This is shown in the following code:

public class myClass{
public void myInstanceMethod(){
  system.debug('This is my instance method');
}

public static void myStaticMethod(){
  system.debug('This is my static method');
}
}

//Construct an instance of myClass and call a method
myClass instanceOfMyClass = new myClass();
instanceOfMyClass.myInstanceMethod();
//Call a static method without instantiating the Class
myClass.myStaticMethod();

We'll discuss triggers and classes in detail in Chapter 4, Triggers and Classes. For now, you just need to be familiar with their names and general use.

 

Summary


That's it for the first chapter. In this chapter, you've already learned a lot about the Salesforce1 Platform and basic Apex concepts. What you should remember from this chapter is that Apex is the proprietary Java-like language of the Salesforce1 Platform. It is strongly typed, case insensitive, and uses single quotes. All statements must end with a semicolon in order to compile. Apex is different from other languages in that it is metadata aware and requires unit testing to be distributed and used in Production environments. Finally, we're sure you won't forget that the Force.com IDE is the preferred tool to develop Apex code and that everything about Apex is documented in Force.com Apex Code Developer's Guide on the Web.

In the next chapter, we'll discuss the limits of Apex and the Salesforce1 Platform. You'll learn about the best practices to avoid them and start working on some code.

About the Authors

  • Matt Kaufman

    Matt Kaufman is no stranger to the Salesforce1 Platform, as he is one of the early employees at salesforce.com. Since 2002, Matt Kaufman has worked with hundreds of businesses to improve their efficiency through Salesforce. He is a certified Salesforce Advanced Administrator, Sales Cloud Consultant, Service Cloud Consultant, Advanced Developer, and Advanced Developer Instructor. His extensive experience and knowledge of salesforce.com technologies cause him to regularly be referred to as Mr. Salesforce, Salesforce wizard, Salesforce genie, and other magically endowed names.

    Matt is currently the chief technology officer of MK Partners, Inc. (www.mkpartners.com), the leading salesforce.com implementation partner in southern California. He regularly provides training and talks on cloud technologies and development. He has also written other publications including Salesforce.com for Dummies and Salesforce.com's Service Cloud for Dummies, Wiley Publishing.

    Browse publications by this author
  • Michael Wicherski

    Michael Wicherski, for the past several years, has been applying his business sense and knowledge towards designing, developing, and implementing custom solutions for hundreds of Salesforce customers, and has worked with clients of varying sizes—from mom-and-pop shops that are just opening to Fortune 100 companies.

    During his time at MK Partners, Michael honed his skills for translating business processes into business logic. He is currently the senior Salesforce developer at The Agency RE, a real-estate firm in the heart of Beverly Hills, where he oversees the day-to-day use of Salesforce; plans, designs, and implements new functionality enhancements; and optimizes those currently in place.

    An avid developer and a nerd at heart, Michael is constantly searching for those bleeding-edge technology innovations that can squeeze that extra bit of efficiency into his work.

    Michael has also collaborated with peers on other publications related to Salesforce, most notably as the technical editor of Salesforce.com for Dummies, 5th Edition.

    Browse publications by this author

Latest Reviews

(3 reviews total)
Excellent
Good
Good
Learning Apex Programming
Unlock this book and the full library for FREE
Start free trial