- SalesforceChaCha
- Posts
- 💃 Shape Shifting Apex Code 🕺
💃 Shape Shifting Apex Code 🕺
Polymorphism explained in Salesforce
Good morning, Salesforce Nerds! Show of hands …
Have you ever stared at your Apex code, wondering if it might qualify as the eighth wonder of the world - for all the wrong reasons? 😰
Perhaps your if-else
chains resemble an ancient scroll, or your overloaded methods are competing for a spot in the Guinness World Records.
Fear not, fellow Salesforce enthusiast! ☁️
Polymorphism, the elegant art of making your code shapeshift with ease, is here to rescue your org (and your sanity)!
In this article, we’ll dive into how polymorphism can transform your Apex from "Why does this exist?" to "Why didn’t I think of this sooner?" 💥
Let’s unravel the magic of writing cleaner, smarter, and infinitely more scalable code. 👇️

TABLE OF CONTENTS
Shape Shifting Apex Code
POLY-WHAT?
WHAT IS IT?
Let’s talk about polymorphism - one of the most misunderstood, underestimated, and yet, most powerful tools in your Apex developer toolbox. 💥
If you’ve ever written lines of Apex that feel like a tangled web of if-else
statements or overloaded methods that spiral out of control, polymorphism might just be exactly what your codebase has been waiting for.
But first, what is polymorphism? 🤔
The term comes from Greek: poly (many) and morphe (forms).
In programming, it means that a single interface can represent different underlying forms (classes).
Think of it as that one friend who can be an accountant 🤓, an artist 🧑🎨, and a chef 🧑🍳- all depending on the context.
Apex supports polymorphism through interfaces, inheritance, and method overriding. 🔥
SOUNDS COOL, WHY THOUGH?
BUT … WHY?
Apex, Salesforce’s programming language, doesn’t often get the same reputation for elegance and sophistication as, say, Java or Python.
But polymorphism is your ticket to writing clean ✨, maintainable 📦️, and scalable 📈Apex code.
Imagine for a second that you’re building functionality for a multi-cloud product company …
Maybe you need to handle different pricing strategies for B2B, B2C, and Partner products.
Without polymorphism, you might use a sprawling if-else
jungle. 😱
With it, you create a clean ✨, extendable solution that you (and future developers) will thank yourself for.
SHAPES OF APEX
A POLYMORPHISM PRIMER
Let’s dive 🤿 into a simple but illustrative example: a zoo.
You have different types of animals: lions 🦁, tigers 🐯, and bears 🐻 - oh my!
Each animal has a unique sound. But, instead of hardcoding behaviors for each, we can leverage polymorphism!
Step 1: Create a Base Class or Interface
public interface Animal {
void makeSound();
}
The Animal
interface declares a method, makeSound()
, that every animal must implement.
Step 2: Implement the Interface
Now, each animal gets its own implementation:
public class Lion implements Animal {
public void makeSound() {
System.debug('Roar!');
}
}
public class Tiger implements Animal {
public void makeSound() {
System.debug('Growl!');
}
}
public class Bear implements Animal {
public void makeSound() {
System.debug('Grunt!');
}
}
Step 3: Write the Polymorphic Code
Here’s where the magic happens:
public class Zoo {
public static void hostAnimal(Animal animal) {
animal.makeSound();
}
}
Now you can call:
Zoo.hostAnimal(new Lion());
Zoo.hostAnimal(new Tiger());
Zoo.hostAnimal(new Bear());
Each animal knows its own sound, and you don’t need to clutter your logic with type-checking. 💯
Why is this better than if-else
?
Let’s rewind ⏪️ and imagine you didn’t use polymorphism. You might write something like this: 🤢
public static void hostAnimal(String animalType) {
if (animalType == 'Lion') {
System.debug('Roar!');
} else if (animalType == 'Tiger') {
System.debug('Growl!');
} else if (animalType == 'Bear') {
System.debug('Grunt!');
}
}
This works fine - until your zoo gets a giraffe 🦒, elephant 🐘, or velociraptor 🦖.
Now you’re stuck updating this method every time a new animal shows up. 🚫
With polymorphism, adding a new animal is as simple as creating a new class that implements the Animal
interface.
No changes to the core logic are required.
PROCEED … WITH CAUTION
REAL WORLD USAGE
Here are three real-world use cases where polymorphism can level up your Salesforce game: 👍️
1. Strategy Pattern for Business Logic
Say you’re implementing custom discounting logic for opportunities. Each account type -Enterprise, SMB, and Non-Profit - has different rules.
Use an interface for the discount logic, and implement a strategy for each account type. At runtime, pick the right implementation. 🙌
public interface DiscountStrategy {
Decimal applyDiscount(Opportunity opp);
}
2. Polymorphism in Triggers
Triggers that need to handle multiple objects can get messy. Use a base handler interface and specific handlers for each object type.
This keeps your logic organized and avoids massive trigger frameworks. 🏗️
3. Dynamic Messaging in Flows
Ever built a process where messages differ based on record type?
Use a base message class and have polymorphic implementations to return customized messages dynamically. 🔥
Beware, there be dragons here!
Like any tool, polymorphism is not without its challenges. Here are two common pitfalls:
Overengineering
Don’t implement polymorphism just because it’s “cool.” If you only have two cases, a simpleif-else
might suffice. Use polymorphism when you expect to scale or need clear separation of concerns. 👈️Difficult Debugging
Debugging polymorphic code can be tricky, especially when multiple classes implement the same interface. Use clear naming conventions and robust logging to keep track of which class is being used at runtime. 👈️
WRAPPING THINGS UP
CLOSING THOUGHTS
Polymorphism is more than a fancy word - it’s a mindset. 🧠
It’s about designing your code to be flexible, scalable, and maintainable. It turns your if-else
jungles into neatly trimmed gardens.
So, the next time you find yourself wrestling with overly complex logic, ask yourself: "Could polymorphism help here?" 🤔
Chances are, it can.
SOUL FOOD
Today’s Principle
"Clean code always looks like it was written by someone who cares."
and now....Salesforce Memes



What did you think about today's newsletter? |