Clojure multimethods vs. protocols

后端 未结 4 1761
北荒
北荒 2020-12-02 17:11

I\'m a Clojure novice and was looking for some concrete examples of when to use protocols and when to use multimethods. I know that protocols are generally geared towards cr

4条回答
  •  生来不讨喜
    2020-12-02 17:20

    Protocol and multimethods are complementary and intended for slightly different use cases.

    • Protocols provide efficient polymorphic dispatch based on the type of the first argument. Because the is able to exploit some very efficient JVM features, protocols give you the best performance.
    • Multimethods enable very flexible polymorphism which can dispatch based on any function of the method's arguments. Multimethods are slower but very flexible

    In general, my advice is to use protocols unless you have a specific case that requires multimethods.

    A case where you could require multimethods is something like the following:

    (defn balance-available? [amount balance] (> balance amount))
    
    (defmulti withdraw balance-available?)
    
    (defmethod withdraw true [amount balance] 
      (- balance amount))
    
    (defmethod withdraw false [amount balance] 
      (throw (Error. "Insufficient balance available!")))
    

    Note that you can't use protocols here for both of the following reasons:

    • The dispatch function needs to use both arguments to determine which method implementation to use (i.e. it is a multiple dispatch case).
    • You also can't distinguish on the type of the first argument (which is presumably always a numeric value)

提交回复
热议问题