The Holy Java

Building the right thing, building it right, fast

Clojure

Clojure-related resources and notes.

Why Clojure(Script)?

Clojure(Script) is simpler yet more expressive (than Java(Script))
– paraphrase of David Nolan in ClojureScript Next

Clojure (and thus ClojureScript) is one of the best designed programming languages, it is really well thought-through and great care is taken to ensure that the pieces do each a different thing yet fit perfectly together. It has been designed after years of painful experiences with production systems in Java, C++, Common Lisp and others to avoid the main sources of complexity and maintenance headaches. (For details see the Clojure Rationale and talks by Rich Hickey such as Effective Programs – 10 Years of Clojure.)

Clojure enables interactive programming – you can connect a REPL to your application and develop it and interact with it from code while it is running. You cannot imagine the power and the insanely short feedback loop until you experience it. See the short screencast Interactive programming Flappy Bird in ClojureScript for an idea.

It has performant immutable data structures that make many concurrency-related defects impossible.

It has a powerful library of data transformation functions that can be effectively combined together.

When necessary, you can use macros to remove duplication and fit the language to your problem.

No matter whether you use Clojure core or a library, they use raw Clojure data – that you can access and transform through the core functions you know and love. No more learning a custom API for every library! (Though you still need to learn and understand its data.)

It has also core.async for asynchronous/reactive programming,  clojure.spec to document, verify, use and test your data, and much more.

Clojure has also an active and friendly community. You always get help in the official Slack organization, one of the mailing lists, and other places.

Nate Wildermuth: ClojureScript and the Blub Paradox

(highlights and [insertions] mine)

That makes the important advantages of ClojureScript hard to perceive, as the essential difference [from JS] belongs in new patterns of problem solving rather than new syntax and grammar.

ClojureScript does the opposite. Instead of seeking to avoid the danger of using one bug-prone function, it provides three types of switch statements, each suited to different kinds of control flow. These options not only allow one to engage in high-level forms of abstraction, but actually encourage this kind of thinking. Moreover, the entire pattern of thought begins at a much higher level, seeking to recognize patterns even before fully understanding the solution. [The same applies for Clojure and Concurrency, having cca 4 ways to manage state instead of Java’s one -makes you think about what/why/how, which is a Good Thing (TM)]

ClojureScript, like JavaScript, doesn’t come with pattern matching. This would be a problem, except that ClojureScript comes with something better: macros.

Some languages run close to the “metal” — […]. Other languages take the opposite approach, running close to the “human metal” — our minds. The closer that a language can express (or in the case of macros, be modified to express) human thoughts, the closer we get to a program that we can understand natively. We no longer need to change our thoughts to fit the language. Instead, we change our language to fit the thoughts.

For beginners

Note: Clojure and productivity

You can be very productive with Clojure, much more than e.g. in Java thanks to its interactive development, simplicity, and powerful tools such as macros. However there are some preconditions, as Eric Normand writes in PurelyFunctional.tv Newsletter 266:

When you don’t have the stuff above (paren[these] management, integrated REPL, hot code reloading, and experience debugging the errors), the [development] cycle can be much slower than the descendants of punchcard languages.

(Fortunately the community is working on providing better beginner user experience, better tools, and better error reporting to alleviate these.)

So to really experience the productivity and pleasure of Clojure(Script), you need:

  1. A tool to enable effective, productive (structural) editing of Clojure code, such as Parinfer
  2. A good editor with an integrated REPL so that you can evaluate your code and interact with your running application in a frictionless way. Cursive (paid for commercial use) and Emacs (powerful but very steep and long learning curve) are the most popular, but there are also special ones for beginners such as Nightcode and (simpler, web-based) Lightmod. (Many editors have some Clojure support but the quality and depth and thus user experience vary a lot.)
  3. ClojureScript: hot code reloading (which Figwheel does perfectly)
  4. Experience debugging errors – sadly you have to learn that though tools such as Ultra/Pretty (see below) and Expound for Spec do help.
  5. Not to hesitate to ask for help and advice at the Clojurians Slack community 🙂

Resources for beginners

Official sources

Help & learning

Community, advice, fora

  • Clojurians – the official Slack organization with channels for Clojure, ClojureScript, and most popular libraries and topics. Leading developers and authors often answer questions.
  • Clojure and ClojureScript Google Groups – for advice, announcements, keeping informed
  • Clojureverse – friendly discussion fora
  • Newsletters to keep updated about the latest development, useful libraries, etc.
  • Podcasts
    • Cognicast by Cognitect, the company behind Clojure – interviews with interesting people
    • defn – “A loud, irreverent podcast discussing the delights of Clojure, ClojureScript with leaders and folks of the Community”

Beginner-friendly tools

  • Beginner-friendly all-in-one IDE: Nightcode and (simpler, web-based) Lightmod
  • Luminus – web “framework,” i.e. a curated and integrated set of libraries for web (backend and frontend) development in Clojure(Script) (developer tools, logging, security etc). So that you don’t need to assemble your own.
  • Editing code
    • Parinfer – provides for efficient and simple structural editing of Clojure/Lisp code using just Tab (compared to the older Paredit with its numerous key-bindings). A must-have for efficient and productive experience with any Lisp.
  • Building and running code
    • Ultra – a Leiningen (the primary Clojure build tool) plugin for an absolutely kick-ass development environment (i.e. REPL) – better stack-traces (via Pretty), human-friendly test output, colors, syntax-highlighting.

 

Style and best practices

Core

  • Threading do’s and don’ts: use -> and ->> only for navigation or transformation; prefer to keep the same type (but the last transf.) – break if necessary; avoid anonymous functions to change order type – likely doing to much already (if really necessary, use as-> which is intended to be used exactly & only inside ->).

Resources

Learning

Libs

Convenience libraries – the missing “features” of clojure.core etc.

  • ztellman / potemkin – “a collection of facades and workarounds for things that are more difficult than they should be” – f.ex. import-vars so that we can expose a single namespace with everything to users while having the code split in multiple files, def-map-type so that we only need to implement the 4 essential functions, def-derived-map – as a view on another object, f.ex. JavaBean, definterface+ – same syntax as defprotocol but creating an interface with its memory/performance benefits => easy to switch, fast-memoize and more
  • cloojure/tupelo (and cloojure/tupelo-datomic) – convenience features “missing” from clojure.core – e.g. the awesome (spy[x[x]]) for logging the expression [+type] going through a threading macro or a fn, …)
  • marick/suchwow – Functions and behaviors not present in Clojure core. Support for creating and using your own “favorite functions” namespace. Better docstrings for clojure.core functions. More expansive versions of clojure.core functions.
  • plumatic/plumbing – Prismatic’s Clojure(Script) utility belt (including Graph – a simple and declarative way to specify a structured computation)
  • weavejester/medley – A lightweight library of useful Clojure(Script) functions (a tighter focus than useful and plumbing, and limits itself to a small set of general-purpose functions.)
  • flatland/useful
  • nathanmarz/specter – querying and manipulation of complex, nested data structures made easy

Web

Development in general

Essential

ClojureScript

  • Chestnut (10/2014) – A Leiningen template for a Clojure/ClojureScript app based on Om, featuring a great dev setup, and easy deployment. Highlight: well-functioning browser-connected REPL, see a demo by D. Nolen who labels it “one of the coolest bits of ClojureScript tech I’ve encountered in a very long time.” The REPL is “always ready to go even if you kill the web server, refresh the web page, or have a JS exception on the page.” and there is live reload upon file change without corrupting the app state.
  • lein-figwheel – Figwheel builds your ClojureScript code and hots loads it into the browser as you are coding – live code and CSS reloading
  • weasel – WebSocket-connected REPL environment for ClojureScript – especially useful if the standard REPL doesn’t work because the page does not allow for iframes and/or does not use http://
  • clj-devtools – Better presentation of ClojureScript values in Chrome DevTools

Testing

  • juxt iota – simplify running multiple checks on a (complex) data structure

Data

Utilities

  • clojure/tools.trace – trace calls, f.ex. run (trace-ns my.ns) to print call with params and return value of each function
  • Schmetterling – Debug running clojure processes from the browser! – upon an exception, the process will pause and S. will show the stack, which you can navigate and see locals and run code in the context of any stack frame; you can also trigger it from your code. It can be used nicely also in pre/post-conditions.

Lein

  • lein-ancient – analyzes your project.clj and lets you know which dependencies are out of date.
  • lein-try – start a REPL with various dependencies without needing a project. Great for exploring new libraries!
  • Eastwood – a lint tool for Clojure.
  • lein-shorthand – a plugin to make useful functions (such as pprint, source) accessible in any namespace by copying them into a new namespace . so you can invoke (./pprint …).

Lib catalog

From Clojure to Java

  • UncleJim (“Unmodifiable Collections for Java™ Immutability”)  is a very interesting looking library, with these main features:
    • Type-safe versions of Clojure’s immutable collections, implementing the generic java.util collection interfaces.
    • A simplified immutable alternative to Java 8 Streams, wrapping checked exceptions and avoiding primitives.
    • A tiny, type-safe data definition language of brief helper functions: vec(), set(), map(), and tup(), (like Clojure’s vector [], set #{}, and map {}).
    • Extend Tuples to make your own immutable Java classes (with correct equals(), hashCode(), and toString() implementations) almost as easily as writing case classes in Scala.

ClojureScript

Cljs: 23kB

(-> (dom/getElement “app”)
(dom/setTextContent (join “, ” [“Hello” “World!”])))

jQuery: 29kB (+ 45kB Immutable.js)

$(“#app”).text(
[“Hello”, “World”].join(“, “));

Source: SeatleJS – ClojureScript for Skeptics by @derekslager

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: