One interesting feature of Clojure that I was able to make use of today is ns-resolve
. This feature allows you to dynamically find a var within a specific namespace. This is especially useful for dynamically calling a function, given a string. I have also used this method in the metis validations project to dynamically load validation functions. Consider the snippet from metis,
(defn get-validation [validatior-key]
(if-let [fn (ns-resolve 'metis.validator.validations (symbol (name validatior-key)))]
fn
(throw (Exception. (str "Could not locate the validator: " (name validatior-key))))))
Here I'm using ns-resolve
slightly differently because this method is within the metis.validator.validations
namespace already. This function is used to retrieve a validation function based upon a keyword. For instance, (get-validation :inclusion)
returns the function inclusion
from the validations namespace. This is allows us to not violate the open/closed principle. Users have access to the entire namespace by only using one method on the namespace. This means that if a new validation is added, the user does not have to change their namespaces imports to use it, they just start using it. In this way, the validator is closed to modification and open to extension.
No comments:
Post a Comment