Search icon CANCEL
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
€36.99
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
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Wicherski Profile Icon Matthew Kaufman
Arrow right icon
€36.99
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
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
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
Estimated delivery fee Deliver to Norway

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Norway

Standard delivery 10 - 13 business days

€11.95

Premium delivery 3 - 6 business days

€16.95
(Includes tracking information)

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
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 123.97
Learning Apex Programming
€36.99
Force.com Enterprise Architecture
€49.99
Apex Design Patterns
€36.99
Total 123.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela