Encapsulation In Apex

0
Sfdcpandaschool

Encapsulation In Apex

Wrapping (or Binding) method and data together into a single unit is known as encapsulation. For example: medical capsule, it is bind with different medicines.

An Apex class is the example of encapsulation. Apex bean is the fully encapsulated class because all the data members are private here.

For example, this is an apex class :

public class MyWrapper
{
	private String name;
      
	public void addToName (String text)
	{
		name = name + text;
	}
}

This apex class combines two properties, name with a method called addToName as well. This is how an apex class combines logic to embody encapsulation in apex.

Chapter:

Association In Apex Classes

What is the Association?

In object-oriented programming (OOPs), Association defines a relation or connection between two separate classes that are set up through their objects. Association indicates how objects know each other and how they are using each other’s functionality as per need.

In Apex programming we can achieve Association via two ways:

Note: As we have seen above, there are two ways to connect two classes either using IS-A-Relationship or HAS-A-Relationship what being a developer you need to understand in which scenario you have to use IS-A Relationship or HAS-A-Relationship.

Inheritance (IS-A-Relationship):

Inheritance in Apex is a mechanism by which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in Apex is that you can create new classes that are built upon existing classes. Whenever you inherit from an existing class, you can reuse methods and fields of parent / super class, as well as you can add new methods and fields also based on the requirements.

Why use inheritance in Apex?

  • For Method Overriding (to achieved runtime polymorphism).
  • For Code Reusability.

Terms used in Inheritance:

  • Class: A class is a concept/prototype/template of common properties, from which objects are created.
  • Child Class/Sub Class: Child class is a class which inherits the other class, known as child class. It is also called extended class, derived class, or sub class.
  • Parent Class/Super Class: Parent class is the class from which a subclass inherits the features. It is also called a Super class or a base class.
  • Virtual: The virtual modifier declares that this class allows for extension and overrides.
  • Override: You cannot override a method with the override keyword in the child class unless the class and method have been defined as virtual.

Syntax Apex inheritance

public virtual class Parent{
  public void display(){
    System.debug(‘This is Parent’);
  }
}

Syntax of Sub/Child class

public class Child extends Parent{
  public void display show(){
    System.debug(‘This is from Child’);
  }
}

Create an object and call method

 
Child c = new Child();
c.show();
c.display();

Output :

This is from child
This is Parent

Chapter :

HAS-A-Relationship in Apex

What is HAS-A-Relationship: It is basically used for code reusability. It means that an instance of a class has a reference to another class or the other instance.

Why use HAS-A-Relationship?

  • For Code Reusability.

Note: Using HAS-A-Relationship, we cannot achieve runtime polymorphism. Only via Inheritance we can achieve runtime polymorphism.

Aggregation: If a class has an entity reference, it is called as Aggregation. Aggregation is a type of HAS-A relationship.

Take an example, Room object contains many chairs. If we take away chairs away from room there is no impact on the existence of Room, as given below.

 
public class Room {
  String roomName;
  Chair ch; //Chair is a class.
}

Composition: If a class has an entity reference, it is known as Composition. Composition is also a type of HAS-A relationship.

Take an example, Room object contains many walls. If we take away walls away from room there will be no existence of Room, as given below.

public class Room {
  String roomName;
  Wall wal; //Wall is a class.
}
Chapter :

Polymorphism In Apex

One name many forms is known as polymorphism or in other words you can say many forms are known as polymorphism.

Real life example of polymorphism: lets take an example, in a college a Director wants to call all HODs for annual meeting so he will just simply publish into notice board that all ALLHOD’S are invited which means one name i.e. ALLHOD’S pointing to all HOD of the college of different departments so by which we can say one name many forms known as polymorphism.

Polymorphism can achieve by two ways:

  • Method Overloading in Apex
  • Method Overriding in Apex

Method Overloading in Apex:

If a class have multiple methods with same name but different parameters (either different length of the arguments or different data types of the arguments), it is known as Method Overloading.

If we have to perform only one operation, with the same name of the methods increases the readability of the program as well as its very logical too.

Let’s suppose if we want to perform addition of the given numbers but there can be any number in arguments as below:

Example of method overloading with different data types of the arguments with same method name like sum.

 
public class MethodOverloadDemo{
  public void sum(Integer no1, Integer no2){
    System.debug(‘Sum of 2 Integer is : ‘+ (no1+no2));
  }
  
public void sum(Decimal no1, Decimal no2){

    System.debug(‘Sum of 2 Integer is : ‘+(no1+no2));
  }
}

To run : Create an object and call methods

 
MethodOverloadDemo mo = new MethodOverloadDemo();
mo.sum(10,20);
mo.sum(10.5, 2.5);

Method Overriding In Apex

If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Apex.

In other words, we can say If a subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Note: Always make sure to achieve method overriding the scope must be of parent and child class relationship and you must have same name method needs to declare into child class with same signature of the method from Parent class to achieve method overriding in Apex.

Usage of Apex Method Overriding

Method overriding is used to provide specific implementation of a method that is already provided by its Parent/Super class. Method overriding is used to achieve runtime polymorphism.

Rules for Apex Method Overriding

  • Method name must be same as in the parent class.
  • Method name must have same parameter as in the parent class’s method.
  • Must be inheritance (IS-A relationship).

Syntax for Method Override

public virtual class Parent {
  public virtual void display() {
    System.debug(‘This is Parent’);
  }
}
public class Child extends Parent{
  public override void display(){
    System.debug(‘This is form Child’);
  }
}
Child ch = new Child();
//OR
Parent ch = new Child();
ch.display();

Output :

Chapter :

Abstraction In Apex

Hiding the complexity and given the functionality known as Abstraction.

Real time example of Abstraction: human beings are speaking because GOD given the functionality to them for speaking but how they are speaking and what all their internal body organs they are using for speaking is completely hidden from them so finally we can say they have a functionality of speaking but complexity is completely hidden from them.

Note: Always make sure, abstraction is always for end users not for developers.

In Apex, abstraction can be achieved via 2 ways:

  • Abstract Class
  • Interface

Abstract Class: There are some points which you always remember while working on abstract class as below:

  • If you are making a class as abstract then there is no rule that you guys need to have abstract method inside the abstract class but vice-versa is not true i.e. if you guys having an abstract method inside a class in this case you guys need to declare that class as abstract.
  • An abstract class can have abstract methods (a method without body is known as abstract method) as well as concrete methods (a method with body is known as concrete method) too.
  • We can have a constructor in abstract class but we cannot instantiate the abstract class which means we cannot create object of abstract class.
  • An abstract class always works with the conjunction of child class which means it is a responsibility of child class to override the abstract method of abstract parent class.

Note: If you want that immediate child class will not override the abstract method of parent class in this case you need declare a child class a abstract class.

Syntax of an Abstract Class

 
public abstract class ApexAbstruct {
public ApexAbstruct() { } // default constructor
public abstract void show(); // abstract method, having no body
  public void dispaly(){	  // concrete method, having body.
    System.debug(‘This is normal method ‘); 
  }
}

Implemented/Child Class

public class ApexClass extends ApexAbstruct{
//Override the abstract method of parent class  
public override void show(){  
    System.debug(‘This is an Astruction example’);
  }
}

Cretae an object and call the methos=d.

ApexClass ap = new ApexClass();
ap.show();

Interfaces: There are some points which you always remember while working on interface as below:

  • All the methods of interfaces are by default abstract Which means you do not need to explicitly write abstract keyword in front of method.
  • No need to define access specifier in front of method because all the methods of interfaces are by default is global.
  • An interface always extends another interface.
  • A class always implements an interface.
  • It is a responsibility of child class to override all the methods of implemented interface as all the methods of interface are by default is abstract.

Note: Interfaces are used to achieve 100% abstraction.

Syntax of an Interface

 
public interface ApexInterface{
  void show();
}

Implemented class

public class Apex implements ApexInterface{
  public void show(){
    System.debug(‘This is Apex interface example’);
  }
}

Create an object and call the method

Apex ap = new Apex();
ap.show();

Output:

Chapter :

Exception Handling in Apex

Exception Handling is a mechanism in salesforce to handle unwanted exceptions or errors in our code without the exception breaking the flow of the code.

This is a practice which allows the developers to handle any exceptions in their code, which allows them to account for any errors in the system. This is a best practice that should be followed while developing apex classes.

Exception handling is done in apex by using the try and catch mechanism, basically any code which can throw an exception is enclosed in a try block and each try block is followed by a catch block which is entered if the try block throws an exception.

 
try{
	// Exception prone Code
}
catch(Exception e){
	// Handle the exception
}

Exceptional Handling – try, catch, finally, throw keywords

Exception occurs during the run time / execution of a program. We have to handle the excretion in code. Like java, apex has exception handling mechanism. Below are the Keywords(try, catch, finally, throw ) related to an Exceptional Handling.

try: This keyword is used to identifies a block of code in which an exception can occur.

Example:

 
try {
    // Your code here
} catch (ListException e) {
    // List Exception handling code here
}

catch: This keyword is used to identifies a block of code that can handle a particular type of exception.

Example:

 
try {
    // Your code here
} catch (ListException e) {
    // List Exception handling code here
}

finally: This keyword is used to identifies a block of code that is guaranteed to execute.

Example:

 
try {
    // Your code here
} catch (ListException e) {
    // List Exception handling code
} finally {
    // will execute with or without exception
}

throw: This keyword is used to throws an exception, signaling that an error has occurred.

Example:

 
public class MyException extends Exception {
    try {
        Integer i;
        if (i < 5)
        throw new MyException();
    } catch (MyException e) {
        // Your MyException handling
        // code here
    }
}

Commonly used exceptions in Apex

1. DmlException
Any problem with DML statement, such as an insert statement missing a required field a record.
Example

 
try {
  Merchandise__c m = new Merchandise__c();
  insert m;
} catch(DmlException e) {
  System.debug(‘The following exception has occurred: ‘ + e.getMessage());
}

2. Limit exception

Governor limits are runtime limits which are enforced by the Apex runtime engine. Because Apex runs in a shared and multi-tenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that code does not take over shared resources. Types of limits that Apex enforces are resources like database, memory, number of script statements to avoid infinite loops, and the number of records being processed in a transaction. If the code exceeds a defined limit, the associated governor fires a runtime exception.

Example

Create an object with label Test Object with only one field Name which is of text type. Write an class that is used to inserts 300 records in Test Object.

public class TestDataController {
  public static Test_Object__c test;
  public static void massInsert(){
  for(Integer count = 0; count < 300; count++){
    test = new Test_Object__c();
    test.Name = ‘data field ‘ + count;
    insert test;
  }
}

now it's time to call the static method from your developer Console as shown below

From that Open Developer Console

TestDataController.massInsert();

Debug -> Open Execute Anonymous Window OR (CTRL + E).

Call TestDataController.massInsert(); as shown above.

Click Execute.

You can see that no rows are updated. The exception is
System.LimitException.

3. List Exception

Any problem with a list, for example attempting to access an index that is out of bound.

Example

 
try{
  List li = new List();
  li.add(10);
  Integer i1 = li[0];
  Integer i1 = li[1]; // List exception
 
}catch(listException le){
  System.debug(‘The Exception is : ‘+le.getMessage());
 
}

4. Math Exception

Any problem with mathematical operation, such as divide by zero.

Example

 
Integer i= 1/0; // System.MathException

5. NullPointer Exception

This type of exception occur when you are trying to call a method with null i.e. if a variable is pointing to null and you are trying to call a method cause a NullPointerException.The exception is caught in our defined catch block and this is what is written to the debug log: The below exception has occurred: Attempt to de-reference a null object.

Example

 
String s;
s.toLowerCase(); // Since s is pointing to null, this call causes 
// a NullPointerException
or
try {
  String s;
  Boolean b = s.contains(‘abc’); // Causes a NullPointerException
} catch(NullPointerException npe) {
  System.debug(‘The following exception has occurred: ‘ + npe.getMessage());
}

6. QueryException:

Any problem with SOQL queries, like assigning a query that returns no records or you can say more than one record to a singleton sObject variable.

Example

 
try {
  // This statement doesn’t cause an exception, even though
  // we don’t have a merchandise with name=’XYZ’.
  // The list will just be empty.
  List lm = [SELECT Name FROM Merchandise__c WHERE Name=’XYZ’];
  // lm.size() is 0
  System.debug(lm.size());
  // However, this statement causes a QueryException because
  // we’re assigning the return value to a Merchandise__c object
  // but no Merchandise is returned.
  Merchandise__c m = [SELECT Name FROM Merchandise__c WHERE Name=’XYZ’ LIMIT 1];
} catch(QueryException qe) {
  System.debug(‘The following exception has occurred: ‘ + qe.getMessage());
}

7. Creating Custom Exceptions

Since you cannot throw salesforce built-in Apex exceptions but can only catch them, you can create custom exceptions to throw in your methods as per your requirement. That way, you can also specify detailed error messages and have much more custom exception handling in your defined catch blocks. To create your custom exception class, extends with the keyword Exception(Which is the super class of all the exception class either built-in or custom). Append extends Exception after your class declaration as given below:

Syntax

 
public class MyException extends Exception {}

Example

 
Public class ContactException extends Exception{}
public class ContactUtility {
  public static void mainProcessing() {
    try {
    insertContact();
    }catch(ContactException me) {
      System.debug(‘Message: ‘ + me.getMessage());
      System.debug(‘Cause: ‘ + me.getCause());
      System.debug(‘Line number: ‘ + me.getLineNumber());
      System.debug(‘Stack trace: ‘ + me.getStackTraceString());
    }
  }
  public static void insertContact() {
    try {
      // Insert Contact without required fields
      Contact m = new Contact();
      insert m;
    } catch(DmlException e) {
      // Something happened that prevents the insertion
      // of Contact objects, so throw a more
      // specific exception.
      throw new ContactException(‘Contact could not be inserted.’, e);
    }
  }
}

Post a Comment

0Comments
Post a Comment (0)