Substitutions allow you to override existing methods in a base class that you cannot modify (for example, the source comes from an external dependency). As a result, Dari substitutes the new methods for the original methods everywhere the base class is used.

A substitution implements the Substitution interface, and it extends the class for which you want to substitute methods. Substitution implementations do not change the underlying parent classes.

The following substitution example changes the behavior of the base com.psddev.dari.db.Record#getLabel method for com.psddev.cms.db.Site objects. The base getLabel method returns the name of the site. The substitution method returns the name of the site, plus an indication of the site’s global access.

public class SiteSubstitution extends Site implements Substitution {

   public String getLabel() {
     boolean isGlobal = as(Site.ObjectModification.class).isGlobal();
     String name = super.getLabel();
     return isGlobal == true
        ? super.getName() + "  (Can be accessed globally)"
        : super.getName() + "  (Cannot be accessed globally)";

In the previous example—

  • Line 5 gets the value of the isGlobal flag. Because this flag was added to the original Site class via a system modification, isGlobal is accessed using the method.
  • Line 6 gets the label of the site. As a subclass of Site, SiteSubstitution can call super methods.
  • Lines 7–9 return the site name plus a parenthetical text string that indicates the site’s global access status.

The label appears in the Brightspot Sites widget.


Substitutions tell Dari to return the child substitution object whenever an instance of the parent class is requested in the code. In the example above, Dari returns SiteSubstitution whenever code retrieves an instance of Site.

Substitution only applies when retrieving existing objects. Substitution does not apply to creating new objects. For example, creating a new Site does not create a new SiteSubstitution object.

See also: