Wednesday, June 28, 2017

What is Apex?


Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects.




When Should I Use Apex?

The Salesforce prebuilt applications provide powerful CRM functionality. In addition, Salesforce provides the ability to customize the pre built applications to fit your organization. However, your organization may have complex business processes that are unsupported by the existing functionality. When this is the case, the Force.com platform includes a number of ways for advanced administrators and developers to implement custom functionality. These include Apex, Visualforce, and the SOAP API.





Apex


Use Apex if you want to:
• Create Web services.
• Create email services.
• Perform complex validation over multiple objects.
• Create complex business processes that are not supported by workflow.
• Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object.)
• Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed,regardless of whether it originates in the user interface, a Visualforce page, or from SOAP API.

Visualforce

Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing the Salesforce user interface. With Visualforce you can:
• Build wizards and other multistep processes.
• Create your own custom flow control through an application.
• Define navigation patterns and data-specific rules for optimal, efficient application interaction.


SOAP API

Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of record at a time and does not require any transactional control (such as setting a Savepoint or rolling back changes).


What is a Method and how to create a Method in Apex?

A Method is a collection of statements that are grouped together to perform an operation.

void doNothing() {}
void doNothingWithArgs(String a, Integer b, Date c) {}
void returnsNothing() { Integer i = 1; }
Integer returnsInteger() { return 2009; }

Creating a Method:

In general, a method has the following syntax:
modifier returnValueType methodName(list of parameters) {
  // Method body;
}

A method definition consists of a method header and a method body. Here are all the parts of a method:

Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.

Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.

Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.

Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.

Method Body: The method body contains a collection of statements that define what the method does.

Ex:-
public static integer  max(integer num1, integer num2) {
      integer result;
      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result;


What is a Data Type and What are the different Data Types are available in Apex?

A data type in a programming language is a set of data with values having predefined characteristics. Examples of data types are: integer, floating point unit number, character, string, and pointer. Usually, a limited number of such data types come built into a language. The language usually specifies the range of values for a given data type, how the values are processed by the computer, and how they are stored.

Apex is a strongly typed, object-oriented programming language. Just like any other  programming language, Apex has variety of data types that you can use.

1).Primitive Types - This data types include String, Integer, Long, Double, Decimal, ID, Boolean, Date, Datetime, Time and Blob. All these data type variables are always passed by value in methods.  Another point to note is in Apex, all variables are initialized to null when declared. You must explicitly initialize to non-null values before using. 



Data Type
Description
Blob
A collection of binary data stored as a single object.
Boolean
A value that can only be assigned true, false, or null. For example:
Boolean isWinner = true;
Date
A value that indicates a particular day. Unlike Datetime values, Date values contain no information about time. Date values must always be created with a system static method.
Datetime
A value that indicates a particular day and time, such as a timestamp. Datetime values must always be created with a system static method
Decimal
A number that includes a decimal point. Decimal is an arbitrary precision number. Currency fields are automatically assigned the type Decimal.
Double
A 64-bit number that includes a decimal point. Doubles have a minimum value of -263 and a maximum value of 263-1. For example:
Double d=3.14159;
ID
Any valid 18-character Force.com record identifier. For example:
ID  ='00300000003T2PGAA0';

Integer
A 32-bit number that does not include a decimal point. Integers have a minimum value of  -2,147,483,648 and a maximum value of  2,147,483,647. For example:
Integer i = 1;
Long
A 64-bit number that does not include a decimal point. Longs have a minimum value of -263 and a maximum value of 263-1. Use this data type when you need a range of values wider than those provided by Integer. For example:
Long l = 2147483648L;
String
Any set of characters surrounded by single quotes. For example,
String s = 'The quick brown fox jumped over the lazy dog.';
Time
A value that indicates a particular time. Time values must always be created with a system static method.


2).sObject Types - This is a special data type in Apex. sObject is a generic data type for representing an Object that exists in Force.com. It could be Standard object like Account, Opportunity etc., or Custom object that you define.  Following are some of the examples of sObject variables -


Sobject s = new Account();
Account a = new Account();
CustomObject__c c = new CustomObject__c();


As you can see above, your custom objects have an extension of __c to distinguish from the Force.com standard objects. Fields from the sObject variable can be accessed using the dot notation. For example


 c.Name = 'Test Name';


3).Collections - Apex has 3 types of collections. Lists, Sets and Maps.

  • list is like an array, a sequential collection of elements with first index position as zero. List can contain elements of primitive types, sObjects, user-defined objects, Apex objects or even other collections. A list can contain up to four levels of nested collections. List can contain duplicate elements.
  • set is also a collection of elements and elements can be of any data type. Unlike list, set contains unique elements and elements in set are not in any specific order.
  • map is a collection of key-value pairs. Keys and values can be any data type. Keys are unique and map elements must be accessed by the key as the order of  map elements are not reliable.


4).Enums - Just like in other programming languages, Enum type represents a fixed set of named constants.

An enum is a data type which contains fixed set of constants. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) ,directions (NORTH, SOUTH, EAST and WEST) etc. The enum constants are static and final implicitly.



After you create an enum, variables, method arguments, and return types can be declared of that type.


ex:-


public enum Season {WINTER, SPRING, SUMMER, FALL}


Once you define your enumeration, you can use the new enum type as a data type for declaring variables. The following example uses the Season enum type that is defined first and creates a variable s of type Season. It then checks the value of the s variable and writes a different debug output based on its value. Execute the following:


public enum Season {WINTER, SPRING, SUMMER, FALL}
Season s = Season.SUMMER;
if (s == Season.SUMMER) {
// Will write the string value SUMMER
System.debug(s);
} else {
System.debug('Not summer.');
}



   }


What is Variable and How to create a Variable in Apex?

The variable is the basic unit of storage in any programming language. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime.


Declaring a Variable :- In Apex all variables must be declared before they can be used. The basic form of a variable. declaration is shown here:


type identifier [ = value][, identifier [= value] ...] ;

Integer i = 0;
String str;
Account a;
Account[] accts;
Set<String> s;
Map<ID, Account> m;

All variables allow null as a value and are initialized to null if they are not assigned another value. For instance, in the following example, i, and k are assigned values, while j is set tonull because it is not assigned:

Integer i = 0, j, k = 1;

Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks cannot redefine a variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:
Integer i;
{
 // Integer i; This declaration is not allowed
}
for (Integer j = 0; j < 10; j++);
for (Integer j = 0; j < 10; j++);

Case Sensitivity :-To avoid confusion with case-insensitive SOQL and SOSL queries, Apex is also case-insensitive. This means:

Variable and method names are case insensitive. For example:

Integer I;
//Integer i; This would be an error.

• References to object and field names are case insensitive. For example:
Account a1;
ACCOUNT a2;

• SOQL and SOSL statements are case insensitive. For example:
Account[] accts = [sELect ID From ACCouNT where nAme = 'fred'];

Constants :- Constants can be defined using the final keyword, which means that the variable can be assigned at most once, either in the declaration itself, or with a static initializer method if the constant is defined in a class. For example:

public class myCls {
  static final Integer PRIVATE_INT_CONST;
  static final Integer PRIVATE_INT_CONST2 = 200;
  public static Integer calculate() {
    return 2 + 7;
  }
  static {
   PRIVATE_INT_CONST = calculate();
  }
}


What is Access Modifier and What are the different Access Modifiers available in Apex?

The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible.

Apex provides a number of access modifiers to help you set the level of access you want for classes as well as the fields, methods and constructors in your classes. A member has package or default accessibility when no accessibility modifier is specified.

private

This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined. If you do not specify an access modifier, the method or variable is private.

protected

This means that the method or variable is visible to any inner classes in the defining Apex class. You can only use this access modifier for instance methods and member variables. Note that it is strictly more permissive than the default (private) setting, just like Java.

public

This means the method or variable can be used by any Apex in this application or namespace.

Note :- In Apex, the public access modifier is not the same as it is in Java. This was done to discourage joining applications, to keep the code for each application separate. In Apex, if you want to make something public like it is in Java, you need to use the global access modifier.

global

This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must also declare the class that contains it as global.

Access Modifiers on Classes
Classes have two access modifiers:

1. public: The class is visible to the entire application namespace, but not outside it.

2. global: The class is visible to Apex code running in every application namespace. If an inner class is global, its outer class is required to be global.

Access modifiers on outer classes are required. Inner classes are private by default, accessible only by their containing classes.

Access Modifiers on Methods and Variables 

Methods and variables have four access modifiers:

1. private: The method or variable is visible only within its defining class.

2. protected: It is visible to the defining class and subclasses.

3. public: It is visible to any Apex code in the same application namespace but not accessible to other namespaces.

4. global: It can be used by any Apex code running anywhere in the organization, in any namespace. If a method is global, its class must be global as well.

If no access modifier is provided, the method or variable is private


What is Class and How to define Class in Apex?

A class is a template or blueprint from which objects are created.For example, the PurchaseOrder class describes an entire purchase order, and everything that you can do with a purchase order. An instance of the PurchaseOrder class is a specific purchase order that you send or receive.

A class can contain variables and methods. Variables are used to specify the state of an object, such as the object's Name or Type. Since these variables are associated with a class and are members of it, they are commonly referred to as member variables. Methods are used to control behavior, such as getOtherQuotes or copyLineItems.

To define a class, specify the following:

1. Access modifiers:
  • You must use one of the access modifiers (such as public or global) in the declaration of a top-level class.
  • You do not have to use an access modifier in the declaration of an inner class.

2. Optional definition modifiers (such as virtual, abstract, and so on)

3. Required: The keyword class followed by the name of the class

4. Optional extensions and/or implementations

Use the following syntax for defining classes:

private | public | global
[virtual | abstract | with sharing | without sharing | (none)]
class ClassName [implements InterfaceNameList | (none)] [extends ClassName | (none)]
{
// The body of the class
}

• The private access modifier declares that this class is only known locally, that is, only by this section of code. This is the default access for inner classes—that is, if you don't specify an access modifier for an inner class, it is considered private. This keyword can only be used with inner classes.

• The public access modifier declares that this class is visible in your application or namespace.

• The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods defined with the webService keyword must be declared as global. If a method or inner class is declared as global, the outer, top-level class must also be defined as global.

• The with sharing and without sharing keywords specify the sharing mode for this class.

• The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method with the override keyword unless the class has been defined as virtual.

• The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined.

Declaring Class Variables :

To declare a variable, specify the following:
• Optional: Modifiers, such as public or final, as well as static.
• Required: The data type of the variable, such as String or Boolean etc...
• Required: The name of the variable.
• Optional: The value of the variable.

Use the following syntax when defining a variable:
[public | private | protected | global | final] [static] data_type variable_name [= value]

For example:

private static final Integer MY_INT;
private final Integer i = 1;

What is interface in Apex and how to create interface in apex?

An interface is like a class in which none of the methods have been implemented the method signatures are there, but the body of each method is empty. To use an interface, another class must implement it by providing a body for all of the methods contained in the interface.

Defining an interface is similar to defining a new class.For example, a company might have two types of purchase orders, ones that come from customers, and others that come from their employees. Both are a type of purchase order. Suppose you needed a method to provide a discount. The amount of the discount can depend on the type of purchase order.

An interface can extend another interface. As with classes, when an interface extends another interface, all the methods and properties of the extended interface are available to the extending interface

Interface:
public interface PurchaseOrder {
// All other functionality excluded
Double discount();
}



Implemented Class:

// One implementation of the interface for customers
public virtual class CustomerPurchaseOrder implements PurchaseOrder {
public virtual Double discount() {
return .05; // Flat 5% discount
}
}

No comments:

Post a Comment