Apex Methods & Polymorphism | Chapter 23 | Salesforce Developer Masterclass
Video Overview & Insights
Welcome to another insightful episode of the Salesforce Developer Masterclass, titled "Apex Methods." In this video, we will explore the fundamentals of methods in Apex, Salesforce’s powerful programming language, and how they are used to encapsulate functionality within classes.
public static Double ageFinder(Date birthDate){
Double age = Date.today().year() - birthDate.year();
if(birthDate.addYears(Integer.valueOf(age))> Date.today() ){
return age--;
}
return age;
}
What are Apex Methods?:
Methods in Apex are blocks of code that perform a specific task or action. They can accept input parameters, process data, and return a result. Understanding how to define and use methods is essential for building modular and reusable code in Salesforce.
public class DamageFromTheMonster {
public Integer heroeLife = 50;
private Integer calculateMonsterDamage (Integer monsterAtk, Boolean wasCritical){
if (wasCritical){
return monsterAtk * 2;
} else {
return monsterAtk;
}
}
public Integer updateHeroeLife (Integer monsterAtk, Boolean wasCritical){
Integer monsterDamage = calculateMonsterDamage(monsterAtk, wasCritical);
heroeLife = heroeLife - monsterDamage;
System.debug('The Heroe survives!! Remaining life: ' + heroeLife);
return heroeLife;
}
}
I probably got carried away, but I hope it's correct 😂
Key Concepts:
Method Declaration: Learn how to declare methods in Apex, including specifying access modifiers (public, private, protected, global), return types, method names, and parameters.
protected is like a family-only recipe or ingredient . it’s hidden from outsiders but passed down to kids who inherit it.
Method Overloading: Explore the concept of method overloading, where you can define multiple methods with the same name but different parameters, allowing for more flexible and expressive code.
Using Apex Methods:
For single line comments, two forward slashes are put.
Creating Methods: See examples of how to create methods in Apex classes, including how to define parameters and return values.
Invoking Methods: Learn how to call methods from other parts of your code, passing arguments and handling return values.
I hope reaching till last video helps me become a developer as a beginner have to watch one video twice 😢
Using void Methods: Understand void methods, which do not return a value, and how they are used for actions that do not require a result.
Best Practices:
Use case must be a little simpler sir😢
Single Responsibility Principle: Follow the principle of single responsibility, where each method should have a single, well-defined purpose.
Code Readability: Write methods that are easy to read and understand, with clear names and well-defined inputs and outputs.
Let's suppose I am parent in a family, i have a car, This car key will only be accessible to all the households (Inner classes), as well as my children and their children and so an do on.
Error Handling: Implement proper error handling within methods to gracefully handle exceptions and ensure the stability of your application.
Common Use Cases:
Great session😇
Data Processing: Methods are often used to process data, such as calculating values, transforming data, or validating inputs.
Integration: Methods can be used to encapsulate logic related to integrating with external systems, such as making HTTP requests or processing responses.
Answer to exercise question: You would use protected when you want a method to be accessible to subclasses or classes that are extended by the class, but nowhere else.
By the end of this video, you’ll have a solid understanding of how to define and use methods in Apex, enabling you to write more modular, reusable, and maintainable code in your Salesforce development projects.
Join us and take your Apex programming skills to the next level by mastering the use of methods in Salesforce.
public class CalculateDiscountAmountpractice {
public static Decimal giveDSAmnt(Decimal sellingprice,Decimal discountpercen ) {
//calculate discount amount.
Decimal DiscountAmount = sellingprice * (discountpercen / 100);
return DiscountAmount;
}
}
call the method;
Decimal DiscountAmount=CalculateDiscountAmountpractice.giveDSAmnt(30,5);
system.debug('Discount : ' + DiscountAmount);
If you want to continue learning Salesforce (for free), Subscribe Salesforce Makes Sense here
https://www.youtube.com/channel/UCl-w-QIXwzSdbIDtpIXclcQ
public class DisccountedAmount{
public static Decimal discAmount(Integer sellingPrice, Decimal discountedPercent){
Decimal finalprice = sellingPrice - ((sellingPrice * discountedPercent)/100);
return finalprice;
}
}
In the Anonymous window to see the output
Decimal finalprice = DisccountedAmount.discAmount(100,10.0);
system.debug(finalprice);
To ensure a smooth learning experience,
I have curated playlists that will help you prepare for interviews, train on specific domains and boost your Salesforce journey.
public class AgeFInder{
public static Double calculateAge(Date dateOfBirth){
Double age = math.floor(dateOfBirth.daysBetween(Date.today()) / 365);
return age;
}
}
In the Anonymous window to see the output
Double age = AgeFInder.calculateAge(Date.newInstance(2002,06,25));
system.debug(age);
30 Scenario Based Questions:
https://youtube.com/playlist?list=PLEKSN4V4WEnIUhgsvAGkT2MZ2JbJtb2KQ
Well done
The Complete Administrator Course
https://youtube.com/playlist?list=PLEKSN4V4WEnLk4FUYHkfUlNbRynwz5cU4
Hi Himanshu
Thank you for the assignments for every topic it is creating interest to learn
public class AgeFinding {
public static Integer ageFinderInYears(Date birthInput) {
Date todaydate=system.today();
Integer currentdate=todaydate.year();
Integer birthdate=birthInput.year();
return currentdate-birthdate;
}
}
we can write code in this way right
Learn Salesforce in Bytes - Short videos on Salesforce features
https://youtube.com/playlist?list=PLEKSN4V4WEnIxdPKa-ZqtWelq65CdR3wH
Hey himanshu, will you also create Asynchronous Apex course. It will be really helpful
Learn Salesforce With Me - Topic based Explanatory Videos
https://youtube.com/playlist?list=PLEKSN4V4WEnLnoTxyKUy6mFcBwSnKDa6q
Great Explanation
65 Salesforce Interview Questions:
https://youtube.com/playlist?list=PLEKSN4V4WEnK93qW9rEQPCM6kLFl99k5u
Thank you Himanshu.
100 Salesforce Interview Questions:
https://youtube.com/playlist?list=PLEKSN4V4WEnLYWAAIidiDkbGimVFEqOK1
Hi Sir, Thank your efforts.
Example of Protected: My Debit card is private, no one can withraw cash from it, but If I share pin to my friend or family member they can do it so. The protected access modifier is much more like private than public. In fact, for a class which is not virtual nor abstract, this access modifier would be the same as private (though it's not allowed). However, once you allow extension of the class, you can then see it in overriding implementations.
If you would like to acknowledge my efforts and want me to continue training and mentoring, you can support me here.
https://www.buymeacoffee.com/HimanshuM
Plz explain about instantiation in detail 😢
For any kind of questions, training & mentorship, queries & concerns,
Feel free to drop a mail at
public with sharing class AgeFinder {
public static Integer ageFinderInYears(Date birthDate) {
// subtract the date provided from current date and divide by usual number of days in one year i.e. 365
return birthDate.daysBetween(Date.today()) / 365;
}
}
salesforcemakessense@gmail.com
That’s all from this video. See you in the next video. Till then, breathe long and keep learning :)
public with sharing class DiscountCalculator {
public Decimal sellingPrice;
public Decimal costPrice;
public Integer discount;
// a method which will find the new selling price after the provided discount is applied
public static Decimal priceAfterDiscountApplied(Decimal costPrice,Integer discount){
// a validation for costPrice should be greather than 100 otherwise no discount applied
// a validation that the discount value cannot be more than 50
Decimal priceAfterDiscount = 0;
if(costPrice < 100 || discount >= 50){
priceAfterDiscount = costPrice;
return priceAfterDiscount;
}
else{
Decimal sellingPrice = costPrice - (costPrice * discount / 100);
return sellingPrice;
}
}
}
More User Perspectives
Hi Himanshu,
If there is a full tutorial on the salesforce developer master class on Udemy, please provide the link. I will buy the course. I can't wait for the day-to-day videos to be posted on YouTube. I hope you will provide the full course Thanks for providing the course i have watched all your videos your explanation is soo good .
Thank you!