Enforcing Proper Directives in Custom Module Routes
I got this tip from another developer and thought it was good enough to share.
One thing you might do when writing custom modules is pass a "directive" in the route. The directive is the portion of the URI that appears after the custom module's prefix:
Inside the custom module, you can read this directive with the
Custom module developers check the directive and perform an action based on its value. This lets you create a single custom module that can perform any number of tasks based on what the route developer might use for the directive.
With custom modules, you can set the directive to be anything you want in the route configuration file, which can be useful for triggering different actions by the module. For example:
(Setting and using directives in custom modules is documented here: Getting the Module Directive.)
But once you start using directives to trigger actions, you have introduced a dependency between the the value of the directive and the action the module takes: what if the route developer doesn't know what directives are available, or what if they enter an incorrect directive?
That's where Java Enums come in. You can enforce the directive that the route developer can use by setting up an enumerated list of valid directives in your module. You then process the directive based on converted Enum values, rather than strings. Here's an example:
Here's an example that uses an Enum to determine if the route developer passed one of several "acceptable" directives. As you can see, the module can take an action based on the value of the directive, or return an error if the directive is not one of the acceptable values:
If the route developer tries to write a route that uses a directive other than one of the Enum values, the route throws an error.