Sharing code and components across managed packages

If you are creating multiple managed packages and want to re-use some code and components in several of them there is no simple solution. (The approach you might take in the Java world of creating a JAR file that contains many related classes that you use in multiple applications is not available.)

You can put the components in a separate managed package, but that is a course-grained approach and has its own set of problems. This post outlines how to use svn:externals (yes this is SVN; I’m unsure about Git) to add shared components into the source tree, so the shared components just become part of each managed package. They pickup the namespace as part of the normal packaging process.

So in the version control system you have an extra project that contains the components you want to share:

  • SharedComponents
  • ManagedPackage1
  • ManagedPackage2

“SharedComponents” can only have dependencies on the core platform; it cannot have dependencies on anything in your managed packages.

Then in the managed package projects, add external file definitions to the svn:externals property of the src folder:

classes/SharedSms.cls              https://.../src/classes/SharedSms.cls
classes/SharedSms.cls-meta.xml     https://.../src/classes/SharedSms.cls-meta.xml
classes/SharedSmsTest.cls          https://.../src/classes/SharedSmsTest.cls
classes/SharedSmsTest.cls-meta.xml https://.../src/classes/SharedSmsTest.cls-meta.xml

where represents the SVN path to the “SharedComponents” project. In this example there are just two classes but each managed package can opt into as few or as many of the components as it needs. The purpose of the “Shared” prefix is to make it clearer in the managed package source where the components come from. (IDEs like Eclipse also decorate the icon of svn:externals to distinguish them.)

Once the svn:externals definition is in place, an SVN update automatically pulls content from both locations. You need to be using at least version 1.6 of SVN; our Jenkins (Continuous Integration server) was set to use version 1.4 by default so that had to be changed to get the builds to work.

Discipline is needed when modifying components in “SharedComponents” to not break any managed package code that depends on them. Running Continuous Integration builds on all the projects will help give early warning of such problems.

Making one DataTable respond to search/length/page changes in another DataTable

DataTables can be applied to multiple tables in a page and sometimes the content in one table needs to be driven by the content in another table. For example, checkboxes in the first table on a page might act as a filter on later tables in a page. (The setup of such filtering is not covered here; the mechanism that can be used is custom filtering.)

But DataTables also supports a search mechanism that reduces the table rows to ones that match and a pagination mechanism where the number of rows shown or the page shown can be changed. By default, changes to those values in the first table will not cause the later tables to be re-filtered and re-drawn. So if you want the later tables to only correspond to the checked checkboxes that are visible in the first table, extra code has to be added.

The good news is that DataTables does generate events for the changes and so provides a convenient point to hook in extra code. The only complication is that it appears necessary to defer until after the current event processing has been completed by using setTimeout.

So assuming the tables are distinguished by classes firstMarker and laterMarker, this code will get the later tables re-drawn (and so re-filtered) to be consistent with the first table:

(function($) {
    $(document).ready(function() {

        var firstTable = $('table.firstMarker');
        firstTable.DataTable();

        var laterTables = $('table.laterMarker');
        var laterDataTables = [];
        laterTables.each(function() {
            laterDataTables.push($(this).DataTable());
        });

        var drawLaterDataTables = function() {
            setTimeout(function() {
                $.each(laterDataTables, function(index, value) {
                    value.draw();
                });
            }, 0);
        };
        firstTable.on('search.dt', drawLaterDataTables);
        firstTable.on('length.dt', drawLaterDataTables);
        firstTable.on('page.dt', drawLaterDataTables);

        // Filtering logic not shown here
    });
})(jQuery.noConflict());

Instanceof for Apex Date and DateTime

Just spent some time chasing a unit test error where the date returned in some code was a day out. The code being tested was:

SObject sob = ...
Object o = sob.get(f);
Date d;
if (o instanceof DateTime) {
    d = ((DateTime) o).date();
} else if (o instanceof Date) {
    d = (Date) o;
}

In the end this unit test demonstrated the cause of the problem:

@IsTest
private class InstanceofTest {
    @IsTest
    static void date() {
        Object o = Date.today();
        System.assertEquals(true, o instanceof Date);
        System.assertEquals(true, o instanceof DateTime);
    }
    @IsTest
    static void dateTime() {
        Object o = DateTime.now();
        System.assertEquals(false, o instanceof Date);
        System.assertEquals(true, o instanceof DateTime);
    }
}

So a Date is a DateTime (as well as a Date) and that was pushing the code through some unwanted timezone offsetting.

A fix is:

SObject sob = ...
Object o = sob.get(f);
Date d;
if (o instanceof Date) {
    d = (Date) o;
} else if (o instanceof DateTime) {
    d = ((DateTime) o).date();
}

and a lesson learned is to be paranoid about the type system in Apex.

Favour the Typesafe Enum pattern in Apex

A frequent need is to have behaviour that varies according to a value such as picklist String value. The simplest approach is to pass that value around as a String and to compare the value against inline String constants or static final Strings declared somewhere. But weaknesses of this approach are:

  • Not typesafe – other values can be accidentally introduced
  • Not self-documenting – using the type String says nothing about the domain/purpose
  • Any related attributes or logic has to be added inline or in a separate class using if/elseif/else chains

(Java had the enum types language feature added in version 5 to address these problems; Apex’s enum language feature is basic in comparison.)

A pattern that addresses these problems and was often recommended in Java before enum types were added is the “typesafe enum” pattern. Here is an Apex example:

public class Status {

    private static final Map<String, Status> STATUSES = new Map<String, Status>();
    
    public static final Status PENDING = new Status('Pending', 5);
    public static final Status OPEN = new Status('Open', 30);
    public static final Status CLOSED = new Status('Closed', 60);
    
    public static Status valueOf(String name) {
        return STATUSES.get(name);
    }
    
    public static Status[] values() {
        return STATUSES.values();
    }
    
    public String name {get; private set;}
    public Integer days {get; private set;}
    
    private Status(String name, Integer days) {
        this.name = name;
        this.days = days;
        STATUSES.put(name, this);
    }
    
    public override String toString() {
        return name;
    }
     
    public Boolean equals(Object o) {
        if (o instanceof Status) {
            Status that = ((Status) o);
            return this.name == that.name;
        }
        return false;
    }
    
    public Integer hashCode() {
        return name.hashCode();
    }
}

Code using it looks like this:

    private void method1() {
        ...
        method2('xyz', Status.OPEN);
        ...
    }
    
    private void method2(String v, Status s) {
        ...
        Date d = Date.now().addDays(s.days);
        String message = 'Status is ' + s;
        ...
    }

To convert a picklist value (or other String) to an instance of this object:

Status status = Status.valueOf(picklistValue);

To iterate over all the values:

for (Status status : Status.values()) {
    ...
}

Extra methods can be added and so can extra data values.

Note that the equals/hashCode methods are only needed if references are serialized. Examples of where that can happen are in Visualforce’s view state or when Database.Stateful is used in a Batchable.

PS

This approach can be used for run-time loaded values (e.g. using describe calls on picklist fields or loading from JSON) though that of course means not having constants for each value. If that is done I strongly recommend lazy loading to avoid filling the debug log with entries for cases where the full set of values are not needed.

Breaking managed package dependencies

We have several managed packages with customers sometimes installing just one of them and other times several of them (depending on the set of features they want). Calls can be needed between the packages: global interfaces and classes defined in one package – lets call it B – are called from another package – lets call it A.

But once the direct calls are added and new managed package versions created, A cannot be installed without B first being installed because the platform’s package dependency approach is rigid and enforced at installation time. This dependency (illustrated with UML dependency notation) is not what we want:

Dependencies

So how to allow managed package A to call managed package B without the fixed dependency? The trick is to have no compile-time dependency between A and B but instead to introduce a third entity C (that could be another managed package or non-namespaced local code) that calls are made through where dependency on both A and B is not a problem:

Broken

Here is an example of the pattern. The API used to illustrate the pattern has a single method to send an SMS (text) message.

The implementation (that we want to use from other packages) is in package B:

global interface Sms {
    global void send(String number, String message);
}

global class Factory {
    global static Sms createSms() {...}
}

In package A the interface is duplicated together with a mechanism to register a type that implements the interface. The package A code references only this interface and class:

global interface Sms {
    global void send(String number, String message);
}

global class Factory {
    global static Sms createSms() {
        // Use name of type from custom setting
        String s = ...;
        Type t = Type.forName(s);
        return (Sms) t.newInstance();
    }
    global static void registerSmsType(Type t) {
        // Store name of type in a custom setting
    }
}

...
    Factory.createSms().send('38383', 'PREZ');
...

Then in C, a class is implemented that has the signature defined in A and delegates to B to do the work. At some point this class name must be registered with A. If C is a managed package that could be in an InstallHandler or it could be a manual configuration step:

global class Sms implements A.Sms {
    global void send(String number, String message) [
        B.Factory.createSms().send(number, message);
    }
}

...
    A.Factory.registerSmsType(Sms.class);
....

So A and B remain independent and C is the “glue” that connects then together. A can be installed on its own and so can B. If they are both installed, then adding the C managed package or non-namespaced local code allows the call between the packages to be made.

PS

Stephen Wilcox’s Apex Calls Between Independent Packages describes the same pattern.

Trigger handler induced design damage

There is a great series of discussions including videos on the subject of the benefits and costs of test driven development. Part of that discussion is the notion of Test-induced design damage where pursuing one principle – testability – to the exclusion of other principles results in damage to the design.

An area in Salesforce where I see risk of damage is the pursuit of this:

Another widely-recognized best practice is to make your Triggers logic-less. That means, the role of the Trigger is just to delegate the logic responsibilities to some other handler class.

quoted from Trigger Frameworks and Apex Trigger Best Practices and often paraphrased. (The term “best practice” is sometimes used to give an idea unmerited gravitas.)

There can be benefits in using separate classes, typically where the logic being implemented has enough complexity to require multiple methods and static constants. Or if a choice has been made to use a carefully selected trigger framework (and not an unproven local invention). And a mixed model – where some code is in the trigger and other parts are moved to classes as needed – also works.

But there are costs:

  • A reduction in cohesion: the logic has moved to a class that is separate from the execution context that includes a number of subtleties as documented in Trigger Context Variables.
  • Over time as more logic is added, the chances of queries being repeated in separate handler class methods or separate handler classes goes up.
  • Some naming challenges: what should the handler class, methods and method parameters be called? And the clutter of more top level classes in an org.
  • Should the test relate to the trigger (the specific context the logic has to run in) or the handler class (with no assumed context)?
  • A risk of failure to bulkify. A handler class that has methods that accept single values rather than collections is an obvious red flag. But with the trigger context not so directly in view when writing the handler class and logic running several method calls down, bulkification can be missed.

Code in a trigger is just like any other code and should be written to Do The Simplest Thing That Could Possibly Work. If the problem being solved can be solved cleanly by keeping the code in the trigger then do that. If not, introduce a class to solve the part of the problem that needs a class. Be prepared to refactor when logic is added later.

The Apex Code Best Practices documentation says “Bulkify your Helper Methods” – if you have any. Those helper methods and classes are not assumed.

Don’t damage your code base by introducing a pattern where the benefits are outweighed by the costs.

Three books all Salesforce developers should read

I’ve recently been writing some Salesforce coding guidelines for new hires that say explicitly what is implicit in our code base. A difficulty is deciding where to stop, so in the end I thought the best thing to do was to also include an as short as possible reading list.

Here is what I chose:

  • Clean Code by Robert C. Martin
    How to write better code. A great book about software craftsmanship whatever language and stack you use.
  • Advanced Apex Programming by Dan Appleman
    The unique features of Salesforce and patterns to address the hard parts. With its help you will be able to write Apex code that works all the time not most of the time.
  • Effective JavaScript by David Herman
    JavaScript is becoming increasingly important. This is a book that will give you real insight into how the language works and the typical patterns you need to use the language well. (I’ve read several modern JavaScript books and I found this by far the best.)

What books would you choose?