| |

Design Patterns in Salesforce (Ep. 5) – What is Polymorphism?

If you ask five developers to define polymorphism, you might get five different answers. But at its core, the concept is simple: it means “having many forms.”

In the world of Salesforce development, polymorphism allows your code to behave differently based on the specific context or “form” it takes at runtime. Instead of writing rigid, monolithic code that breaks every time a requirement changes, polymorphism lets you build flexible, adaptable systems.

In this post, we’ll break down the three main ways to achieve polymorphism in Apex, which ones you should actually use, and why Interfaces are often the best tool for the job.


1. Dynamic Polymorphism (Method Overriding)

The most common entry point into polymorphism is through inheritance. This is often called dynamic polymorphism because the behavior of a method is determined at runtime.

The Scenario: Lead Scoring

Imagine you have a generic LeadScorer class. You have a calculateScore() method that returns a default score of 10.

However, your Marketing Team and Sales Team have different scoring logic. Marketing wants a score of 20, while Sales sticks with 10.

Instead of writing if-else statements to check the user’s department, you can use Method Overriding.

  1. Create a Virtual Base Class: Mark your parent class and method as virtual. This gives other classes permission to extend and modify them [10:04].
  2. Extend the Class: Create a MarketingLeadScorer class that extends LeadScorer.
  3. Override the Method: Use the override keyword to define the specific marketing logic.

Apex

public virtual class LeadScorer {
    public virtual void calculateScore() {
        System.debug('Score: 10');
    }
}

public class MarketingLeadScorer extends LeadScorer {
    public override void calculateScore() {
        System.debug('Score: 20'); // Marketing specific logic
    }
}

Now, when you call calculateScore() on a MarketingLeadScorer instance, Apex automatically runs the marketing version. You didn’t change the base code, yet the form changed [16:13].


2. Static Polymorphism (Method Overloading)

Another form of polymorphism is Method Overloading. This happens when you keep the method name the same but change the parameters it accepts.

For example, you might have:

  • calculateScore()
  • calculateScore(Integer rating)

While this is technically polymorphism (the method takes different forms), it is often discouraged in complex enterprise systems [23:44].

Why avoid it? It can make your classes massive and confusing. If you have 10 different ways to calculate a score, your single class becomes a “God Object” that is hard to read and maintain.


3. The Gold Standard: Interfaces

While inheritance (Method Overriding) is useful, it comes with baggage. When you extend a class, you inherit everything—even methods you don’t need.

What if the Marketing team needs to Score leads but doesn’t need to Convert them? If you use inheritance, they might get stuck with a convertLead() method they never use.

This is where Interfaces shine. They provide the ultimate flexibility by defining a “contract” rather than an implementation [29:56].

Implementing the Interface Pattern

Instead of a parent class, you define an interface that simply says: “If you implement me, you must have a scoreLead method.”

Apex

public interface LeadScoreInterface {
    void scoreLead();
}

Now, your classes can implement only what they need:

  • Marketing Class: Implements LeadScoreInterface.
  • Sales Class: Implements LeadScoreInterface AND LeadConversionInterface.

The Real Power: Dependency Injection

The true magic happens when you build a service that accepts the Interface rather than a specific class.

Apex

public class LeadScoringService {
    public void runScoring(LeadScoreInterface scorer) {
        scorer.scoreLead();
    }
}

You can now pass any class that implements LeadScoreInterface into this service. Whether it’s the Marketing scorer, the Sales scorer, or a totally new HR scorer you build next year—the service works without a single line of code changing [46:33].


Summary: Why Use Polymorphism?

  • Flexibility: You can swap out business logic without rewriting your core services.
  • Decoupling: Your Marketing logic lives in a Marketing file; your Sales logic lives in a Sales file. Breaking one doesn’t break the other [26:41].
  • Cleanliness: By using Interfaces, you avoid the “bloat” of parent classes and ensure classes only contain the methods they actually need.

Polymorphism is about making your code “future-proof.” By designing your system to handle different forms today, you save yourself the headache of refactoring it tomorrow.


For a full code walkthrough and to see these examples built in real-time, check out the full episode: Design Patterns in Salesforce (Ep. 5) – What is Polymorphism?


Need help with your Salesforce Org?

If you need help with your Salesforce org, schedule an hour of consulting time with me! I’m one of only ~500 Salesforce Certified Technical Architect’s (CTA) worldwide and I’ve spent over 30,000 hours building Salesforce implementations over the last decade!

Schedule and hour of consulting with me here!


Do you want to be the next Salesforce Certified Technical Architect (CTA)?

If you need training to help you on your journey to complete your Salesforce CTA Board then why not sign up for the cheapest Salesforce CTA course out there, with someone who has training over a million Salesforce professionals worldwide! You can check out and enroll in the course below!

Sign up for the CTA course here!

Or if a course isn’t your thing, you can always sign up for an hour long CTA study session with me here:
Schedule 1-on-1 CTA Coaching Here!


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture


AI DISCLAIMER: Gemini assisted me in writing this blog post by analyzing and summarizing the contents on the YouTube video I created that is linked at the top of this post.

Similar Posts