Sub topic 12
Package version references and version-aware Apex
This chapter assumes you can read a sfdx-project.json file, know what a namespace is, and have installed a package into an org. It also assumes you have written Apex classes and tests. You will learn how a component records which package version it was written against. You will also learn how code inside a managed package can use that record to keep older behavior for older callers.
The problem this solves
A managed package is installed in many subscriber orgs, and each org has its own code that calls the package. Suppose you ship version 2.0 and change what a method returns. Subscriber code written against 1.0 now gets different behavior, even though the subscriber changed nothing.
The platform handles this with two mechanisms:
- Package version references. Each subscriber component records which version of the package it was saved against.
- Version-aware Apex. Code in the package can ask which version the caller is using and branch on the answer.
Both apply to managed packages, which have a namespace. An unlocked package without a namespace has no namespace to reference. The version number still exists, but other code does not pin to it in the way described here.
Package version references
When you save a component that uses a managed package, the platform stores the package version it was saved against. You see this as a packageVersions element in the component's -meta.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<packageVersions>
<majorNumber>1</majorNumber>
<minorNumber>0</minorNumber>
<namespace>acme</namespace>
</packageVersions>
<status>Active</status>
</ApexClass>The entry says that this class refers to the acme package at version 1.0. A few details matter:
- Only
majorNumberandminorNumberare recorded. Patch and build numbers are not part of the reference. - There is one
packageVersionsentry per managed package the component uses. - The entry appears on components that can reference packages, such as Apex classes, Apex triggers, and Visualforce pages.
- The reference stays fixed when a newer package version is installed. Your component keeps pointing at 1.0 until you change the reference and save it.
This is the pin that protects older callers. Installing 2.0 does not change what the class in the example sees, because its recorded reference is still 1.0.
Where references are set
You rarely write packageVersions by hand. The platform fills it in when you create or save a component in an org that has the package installed. If you retrieve that component with the CLI, the entry comes back in the -meta.xml file. If you deploy it to another org, the referenced package version must be installed there at that version or later. Otherwise the deployment fails.
The next table summarizes who sets what.
| Item | Who sets it | When it changes |
|---|---|---|
| `apiVersion` | Developer or tooling | When you edit the component and choose a new API version |
| `packageVersions` entry | Platform, when the component is saved | When you re-save the component against a newer package version |
| Package version installed in the org | Administrator or CI job | When a new version is installed |
The last row is separate from the second. A newer installed version does not rewrite the references in existing components.
How the request version flows
Inside the package, Apex can call System.requestVersion(). It returns a Version object holding the major and minor numbers of the package version that the calling code references.
The diagram shows the flow.
The installed version is 2.0, but the answer depends on the caller's reference. A subscriber class saved against 2.0 would get a different branch from the same method.
Writing version-aware Apex
Here is a class in a managed package that keeps old behavior for old callers:
global with sharing class Greeter {
global static String greet() {
if (System.requestVersion().compareTo(new Version(2, 0)) < 0) {
return 'Hello';
}
return 'Hello, welcome';
}
}Points to note:
globalmakes the class and method visible to code outside the package. Subscriber code can only callglobalmembers of a managed package.Version.compareToreturns a negative number if the version is lower than the argument, zero if equal, and a positive number if higher. So< 0means "older than 2.0".- The version in
new Version(2, 0)is the version where the behavior changed. Keep that number in a comment or a constant so you can find it later.
Testing each branch
You can test the old branch without installing the old package. In a test method, System.runAs accepts a Version and runs the block as if the caller referenced that version:
@IsTest
private class GreeterTest {
@IsTest
static void oldCallersGetOldGreeting() {
System.runAs(new Version(1, 0)) {
System.assertEquals('Hello', Greeter.greet());
}
}
@IsTest
static void newCallersGetNewGreeting() {
System.runAs(new Version(2, 0)) {
System.assertEquals('Hello, welcome', Greeter.greet());
}
}
}Write one test per branch. A version check that is never exercised for the old path is a common source of regressions, because nobody notices until a subscriber upgrades.
What you cannot change freely
Version-aware code is only half of the compatibility story. The platform also restricts what you may remove from a managed package between versions. This is the link back to ancestry, which the previous chapter covered. When a new version has a released ancestor, the rules for that ancestor apply. In practice:
- You cannot delete a
globalApex class, method, or variable that shipped in a released version. Subscriber code may call it. - You can mark a global item with the
@deprecatedannotation. Existing callers keep working. New code written against the newer version cannot see the item. - You can add new global members.
- Changing a global signature, such as parameter types or the return type, counts as breaking and is not allowed. Add a new method instead.
Version-aware branches let you change what a method does. They do not let you change what a method is. If the signature must change, add an overload or a new method and deprecate the old one.
Common mistakes
- Assuming an upgrade changes subscriber references. It does not. If a subscriber reports that new behavior is missing after an upgrade, check the
packageVersionsentry in their component. It may still say the old version. - Calling
System.requestVersion()from code that is not packaged. The method is meant for code that runs inside a managed package, where there are callers with different references. Do not use it as a general version lookup in your own org. - Gating on the wrong boundary. Using
<= 0instead of< 0against the version where behavior changed moves the boundary by one release. Write the comparison to match the sentence "callers older than X keep the old behavior." - Forgetting to test the old branch. Without
System.runAs(Version), only the newest behavior is covered by tests. - Deploying a component to an org with an older package installed. The deployment fails because the reference points to a version that org does not have. Install the required version first. This is the same ordering problem described in the earlier chapters on installation order.
A short workflow
- Release version 1.0 with
greet()returningHello. - Subscribers write classes that call
Greeter.greet(). Their-meta.xmlfiles recordacmeat 1.0. - In the next version, change
greet()to branch onSystem.requestVersion(), and set the version number to 2.0.0.NEXT insfdx-project.json. - Add the two tests above and create the package version with code coverage.
- Promote and release the version.
- Install it in a subscriber org. Existing classes still get
Hello. A class saved after the upgrade, against 2.0, getsHello, welcome.
Exercise
A subscriber org has your managed package installed at version 2.1. One of their Apex classes has a packageVersions entry with majorNumber 1 and minorNumber 3. Your package method checks System.requestVersion().compareTo(new Version(2, 0)) < 0. Which branch runs when that class calls the method, and what must the subscriber do to get the newer behavior?
Show answer
The older branch runs, because the caller's reference is 1.3, which is less than 2.0. The installed version (2.1) does not matter. To get the newer behavior, the subscriber must re-save the class against the newer package version so that its packageVersions entry records 2.0 or higher.
Exercise
You released a package where global static Integer total(List<Integer> values) exists. In the next version you want it to take a Set<Integer> instead. Can you change the signature? What should you do?
Show answer
No. Changing a released global signature is a breaking change and is not allowed. Add a new method that takes a Set<Integer> (for example an overload), and mark the old method with @deprecated so that existing callers keep working.