Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Apex Programming

You're reading from   Learning Apex Programming Create business applications using Apex to extend and improve the usefulness of the Salesforce1 Platform

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher
ISBN-13 9781782173977
Length 302 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (11) Chapters Close

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

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.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image