Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning Apex Programming
Learning Apex Programming

Learning Apex Programming: Create business applications using Apex to extend and improve the usefulness of the Salesforce1 Platform

Arrow left icon
Profile Icon Wicherski Profile Icon Matthew Kaufman
Arrow right icon
Free Trial
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.8 (6 Ratings)
Paperback Jan 2015 302 pages 1st Edition
eBook
NZ$39.99 NZ$57.99
Paperback
NZ$71.99
Subscription
Free Trial
Arrow left icon
Profile Icon Wicherski Profile Icon Matthew Kaufman
Arrow right icon
Free Trial
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.8 (6 Ratings)
Paperback Jan 2015 302 pages 1st Edition
eBook
NZ$39.99 NZ$57.99
Paperback
NZ$71.99
Subscription
Free Trial
eBook
NZ$39.99 NZ$57.99
Paperback
NZ$71.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning Apex Programming

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.

The Force.com IDE

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.

The Force.com IDE

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.

    The Force.com IDE

    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!

    Getting comfortable with Eclipse

    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.

Getting comfortable with Eclipse

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.

Linking Eclipse to the Salesforce1 Platform

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.

Left arrow icon Right arrow icon

Description

If you are a developer who has some object-oriented programming experience, Learning Apex Programming is the perfect book for you. This book is most appropriate for developers who wish to gain an understanding of the Force.com platform and how to use Apex to create business applications.

Who is this book for?

If you are a developer who has some object-oriented programming experience, Learning Apex Programming is the perfect book for you. This book is most appropriate for developers who wish to gain an understanding of the Force.com platform and how to use Apex to create business applications.

What you will learn

  • Create an Eclipse workspace and a sandbox, and learn about IDE best practices
  • Write code within the limits of the platform and discover the best practices to stay out of trouble with queries
  • Understand transactional and batch processes
  • Discover classes and triggers and the best practices for using both
  • Design a Visualforce page using Apex and JavaScript
  • Customize sites to display Visualforce pages to the world
  • Integrate Google and Salesforce calendars

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 31, 2015
Length: 302 pages
Edition : 1st
Language : English
ISBN-13 : 9781782173977
Vendor :
Salesforce
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 31, 2015
Length: 302 pages
Edition : 1st
Language : English
ISBN-13 : 9781782173977
Vendor :
Salesforce
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 240.97
Learning Apex Programming
NZ$71.99
Force.com Enterprise Architecture
NZ$96.99
Apex Design Patterns
NZ$71.99
Total NZ$ 240.97 Stars icon

Table of Contents

10 Chapters
1. Apex Assumptions and Comparisons Chevron down icon Chevron up icon
2. Apex Limits Chevron down icon Chevron up icon
3. More and Later Chevron down icon Chevron up icon
4. Triggers and Classes Chevron down icon Chevron up icon
5. Visualforce Development with Apex Chevron down icon Chevron up icon
6. Exposing Force.com to the World Chevron down icon Chevron up icon
7. Use Case – Integration with Google Calendar Chevron down icon Chevron up icon
8. Creating a Property Management Application Chevron down icon Chevron up icon
9. Test Coverage Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Half star icon Empty star icon Empty star icon 2.8
(6 Ratings)
5 star 16.7%
4 star 33.3%
3 star 0%
2 star 16.7%
1 star 33.3%
Filter icon Filter
Top Reviews

Filter reviews by




raghava narayana Sep 29, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
good information
Amazon Verified review Amazon
Sreenivasa Venkateshmurthy Jul 06, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Very good book for programming background people with clear explanations of the examples.
Amazon Verified review Amazon
pgonzaleznetwork May 18, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I haven't read the whole book yet, in fact I'm only on chapter 3. The book has some good recommendations on how to avoid hitting governor limits and pretty much everything up to this point (chapter 3) is about how to code within the apex governor limits, which is good!The downsides is some of the code in chapter 2 and 3 has some typos and in some occasions it is not explained how to run said code. For example, in chapter 2 there's a common trigger pattern but there's no explanation on how to pass the trigger.newMap/oldMap maps to the class in question. Someone completely new to apex would probably be confused by this.For that reason, I wouldn't recommend this book to someone completely new to apex, but instead to someone like me, who's familiar with apex but at a beginner level (I'm familiar with DML, SOQL, SOSL, classes, triggers, etc) and who's not yet confident in writing production code.
Amazon Verified review Amazon
Reji Oct 17, 2018
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
Even though the preface page confirms that "you need not be an expert to read through the content in the book",the reality is opposite. The content looks like a strip down version of a even bigger book and covers concepts in code tuning. All concepts are taken in the lines of performance and Governor limits. So if you think you just need tuning skills and tips for better design principles, this book is for you. Beginner... You may not need this book as of now.
Amazon Verified review Amazon
Cane Jun 08, 2016
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
Inhalt des Buches ist ein netter Rundumschlag für alle, die keine Lust auf die offiziellen Dokus haben und gerne einen Überblick über die Force.com-Plattform als Entwicklungsumgebung suchen.Leider ist es damit auch höchstgradig redundant: Es gibt kaum Inhalte, die nicht in den offiziellen, sehr guten Entwicklerguides stehen. Dazu kommt, dass die Überschriften - vermutlich als Stilmittel - keinen konkreten Bezug zum Kapitelinhalt haben sondern primär Anspielungen auf diverse Filme und Zitate sind. Sie sollen wohl witzig klingen, machen damit aber das komplette Inhaltsverzeichnis unbrauchbar und degradieren das Buch damit zu einer unstrukturierten Aneinanderreihung von belanglosen Inhalten.Ein Auszug gefällig? Hier die Inhalte von Kapitel 4 "Triggers and Classes":A brief history of triggersTrigger happyPulling the triggerInside the mind of a triggerClass is in sessionStaying classyPut your hands togetherBehind the scenesThe Pablo Picasso of ApexDas zieht sich durch das gesamte Buch.Ich empfehle als Alternativen ganz eindeutig die offiziellen Docus (als Einstieg "Apex Workbook" und "Force.com Platform Fundamentals", zur Vertiefung dann "Force.com Apex Code Developer's Guide", "Visualforce Developer's Guide" und "Force.com SOQL and SOSL Reference"). Wirklich nützlich ist jedoch das Buch "Advanced Apex Programming" von Dan Appelmann. Dieses lieferte echte Inhalte, die über die offiziellen Guides weit hinaus gehen.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.