Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving Clojure circular dependencies

I'm working on some Clojure code that has some circular dependencies between different namespaces and I'm trying to work out the best way of resolving them.

  • Basic issue is that I get a "No such var: namespace/functionname" error in one of the files
  • I tried to "declare" the function but then it complains with: "Can't refer to a qualified var that doesn't exist"
  • I could of course refactor the entire codebase but that seems impractical to do every time you have a dependency to resolve..... and might get very ugly for certain networks of circular dependencies
  • I could separate out a bunch of interfaces / protocols / declarations into a separate file and have everything refer to that.... but that seems like it would end up getting messy and spoil the current nice modular structure that I have with related functionality grouped together

Any thoughts? What is the best way to handle this kind of circular dependency in Clojure?

like image 530
mikera Avatar asked Jun 21 '10 11:06

mikera


2 Answers

I remember a number of discussions on namespaces in Clojure -- on the mailing list and elsewhere -- and I have to tell you that the consensus (and, AFAICT, the current orientation of Clojure's design) is that circular dependencies are a design's cry for refactoring. Workarounds might occasionally be possible, but ugly, possibly problematic for performance (if you make things needlessly "dynamic"), not guaranteed to work forever etc.

Now you say that the circular project structure is nice and modular. But, why would you call it that if everything depends on everything...? Also, "every time you have a dependency to resolve" shouldn't be very often if you plan for a tree-like dependency structure ahead of time. And to address your idea of putting some basic protocols and the like in their own namespace, I have to say that many a time I've wished that projects would do precisely that. I find it tremendously helpful to my ability to skim a codebase and get an idea of what kind of abstractions it's working with quickly.

To summarise, my vote goes to refactoring.

like image 79
Michał Marczyk Avatar answered Oct 01 '22 19:10

Michał Marczyk


I had a similar problem with some gui code, what I ended up doing is,

(defn- frame [args]
  ((resolve 'project.gui/frame) args))

This allowed me to resolve the call during runtime, this gets called from a menu item in frame so I was 100% sure frame was defined because it was being called from the frame itself, keep in mind that resolve may return nil.

like image 23
Hamza Yerlikaya Avatar answered Oct 01 '22 18:10

Hamza Yerlikaya