Versioning Apex Code

When subscribers install multiple versions of your package and write code that references Apex classes or triggers in your package, they must specify the version that they’re referencing.

Within the Apex code that is being referenced in your package, you can conditionally execute different code paths based on the version setting of the calling Apex code that is making the reference. The package version setting of the calling code can be determined within the package code by calling the System.requestVersion method. In this way, package developers can determine the request context and specify different behavior for different versions of the package.

The following sample shows different behavior in a trigger for different package versions:

1trigger oppValidation on Opportunity (before insert, before update) {
2
3    for (Opportunity opp : Trigger.new){
4    
5        // Add a new validation to the package
6        // Applies to versions of the managed package greater than 1.0
7        if (System.requestVersion().compareTo(new Version(1,0)) > 0) {
8            if (opp.Probability >= 50 && opp.Description == null) {
9                opp.addError('All deals over 50% require a description');
10            }
11        }
12
13        // Validation applies to all versions of the managed package.
14        if (opp.IsWon == true && opp.LeadSource == null) {
15            opp.addError('A lead source must be provided for all Closed Won deals');
16        }
17    }
18}

To compare different versions of your Apex classes, click the Class Definition tab when viewing the class details.

For more information about the System.requestVersion method, see the Apex Developer Guide.