Organizing Clojure code - A real problem?

I think the lack of framework might mean there is a lack of teaching. Often time people use a framework, or want to know how to organize their code, but they don’t know why it is organized as such, and why the way the framework organizes things is good/bad. That serves as a learning point, they first learn that way of organizing things, and eventually learn of its issues as well. That starts to give them an understanding of the pros/cons of that framework. Then they can try another framework, and another, at which point they begin to have their own intuition into code organization. So I agree lack of framework means we don’t have a curriculum to follow for learning about these things, people are thrown into the deep end directly.

I think we lack examples around this area. Honestly, I’m not finding a lot of blog posts, or article about it. And some of the ones that try are too theoritical.

The simplest way to start organizing Clojure code is to have everything in one giant namespace. But I get so much resistance to this from beginners to Clojure. I keep saying, yes, put it all in one big namespace, what’s the problem? And they don’t know the problem, but it feels wrong to them. I say, editors now can easily handle a relatively large file, and it’s much easier to search within one file than across many. Clojure will enforce organization within a namespace, because everything after depends only on what comes before. Put everything in one namespace and don’t use declare.

This will take you really far already. Now if you feel things have gotten simply too big that your editor lags, ok, break it up, how you ask? Just take the half point and move it to another namespace.

Ok, but there’s a few things you need to not do that other languages will have thought you to do. Don’t put all your defs at the top of the file. Put them right above the thing that first uses them. Don’t group functions by anything, simply make sure that functions that use others are relatively close to each other as much as possible.

As you do that, groups of defs and defns will naturally form in your namespace, you’ll start seeing sections forming where the defs and defns are only used within that section, when that happens, put a big header comment around the section and give it a name.

;;;; Permission handling

Now you can just search for ;;;; and you find all sections in the namespace which lets you navigate your code pretty easily.

I think this is a good starting place for most Clojure code base. Yet it seems it’s proven a really hard advice for people to be convince of and actually try it.

15 Likes