The REPL

The REPL

Readable Clojure, debugging, and UI state machines
View this email in your browser

The REPL

-main

Libraries & Books.

  • re-mote is a REPL driven environment for remote operations on other machines

People are worried about Clojure. ?
The last few weeks have had a lot of discussion about Clojure, its problems, and its future.

Tools.

  • circleci.test is a new test runner that replaces the lein test runner. It has some very cool features like checking for IO in your tests and failing if you haven't marked the test as doing IO.

Recent Developments.

Learning.

Misc.

Copyright © 2017 Daniel Compton, All rights reserved.


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list

Email Marketing Powered by MailChimp

Permalink

Inline Def: An Effective Debugging Technique for Clojure

Clojure beginners often hear that inline def is bad style. For code you commit that’s mostly true. Example:

1
2
3
(defn foo [x]
  (def y (+ x 1))
  y)

Here def performs a side effect every time you call foo, by (re)defining a Var y which is global to the current namespace. Instead you should use let to make it a local:

1
2
3
(defn foo [x]
  (let [y (+ x 1)]
    y))

However, inline defs can serve a useful purpose, namely that of a simple debugger. Debuggers for Clojure exist, e.g. in CIDER, but I mostly forget to use them. After println, inline def is my debugging tool of choice.

Example:

1
2
(defn foo [& [{:keys [a b c] :as m}]]
  (+ a b c))

How should I call this function? Of course.

1
2
(foo :a 1 :b 2 :c 3)
;; => java.lang.NullPointerException

Wait, what? Inline def to the rescue.

1
2
3
4
5
6
7
(defn foo [& [{:keys [a b c] :as m}]]
  (def m m)
  (+ a b c))

(foo :a 1 :b 2 :c 3)
;; => java.lang.NullPointerException
m ;;=> :a

Oh, of course! What happened is that m was bound to the first argument. I get it, I should have called foo like this:

1
(foo {:a 1 :b 2 :c 3}) ;;=> 6

Time to remove the inline def and get on with life.

I regularly use this technique to capture a giant piece of input that is part of some processing chain. Recently I was working on some XML parsing. For every XML file this function was called:

1
2
3
4
(defn process-xml [xml-as-str]
  (def x xml-as-str)
  ;; processing
  )

That function was part of larger flow that reads from a directory of zipfiles containing XML files. After processing a few files I would get an exception. Let’s inspect x, the last input that triggered the exception.

1
x ;;=> ""

So the last entry from the zipfile was empty. Turns out the entry was not an XML file, but a directory represented by an empty string. Another example involved some XML file that didn’t have the format I expected. Every time I got a new exception I could quickly see what was going on and retry process-xml with x without kicking off the flow from scratch.

1
(process-xml x) ;;=> ok, now it works!

Next time you have the urge to reach for a debugger, you might want to become friends with inline def first.

Permalink

Simple and Happy; is Clojure dying, and what has Ruby got to do with it?

The past week or so a lot of discussion and introspection has been happening in the Clojure community. Eric Normand responded to my one year Lambda Island post with some reflections on the size and growth of the community.

And then Zack Maril lamented on Twitter: “I’m calling it, clojure’s dying more than it is growing”. This sparked a mega-thread, which was still raging four days later. A parallel discussion thread formed on Reddit. Someone asked if their were any Clojure failure stories. They were pointed at this talk from RubyConf 2016, which seemed to hit a lot of people right in the feels, and sparked a subthread with a life of its own.

Meanwhile Ray, one of the hosts of the defn podcast reacted to the original tweet: “I’m calling it: Clojure is alive and well with excellent defaults for productive and sustainable software development.” This sparked another big thread.

Finally @phillmv, the person who did the talk that sparked so much debate, wrote his own summary of the discussion while reiterating some of his points in a blog post: Simple Ain’t Easy, but Hard Ain’t Simple: Leaving Clojure for Ruby.

It was all a bit much to be honest, but if we care about a healthy and growing Clojure community then it’s important that we have these conversations. Let’s try to unpack some of the points that were raised.

Clojure is dying

This statement initially set fire to the whole debate, but there seems to be little proof that this is true. This ask HN thread about who’s using Clojure shows plenty of companies adopting it recently. The list of companies on Clojure.org mentions Amazon, Facebook, Deutsche Bank, eBay, PayPal, Oracle, ThoughtWorks, Red Hat, Salesforce, Walmart, and 271 others. Onyx raised 500’000$US in funding last year, and the Taiwanese government is using Clojure for its citizen participation platform.

The community Slack grew from just over 6000 to close to 10K members in the past 12 months. Meetup.com lists 432 meetup groups that mention Clojure. We could definitely use more Clojure conferences, but with 8 annual conferences worldwide there are already twice as many as a few years back, and most of them seem to be growing in size year on year.

One personal observation: at my first EuroClojure in Berlin in 2013, most people I spoke to were enthusiasts. They programmed Java or Ruby or C# at their day jobs, and were dreaming of landing a Clojure job one day. At last year’s EuroClojure in Bratislava it was the opposite, it seemed most people were doing Clojure professionally in some shape or form.

So it seems industry adoption has grown significantly, and continues to gather steam. Mindshare in the open source and developer enthusiast communities has grown more slowly, and it’s worthwhile asking why that is.

“Simple vs. Easy” vs. “Programmer Happiness”

What also hit the internet last week was David Nolen’s talk from GOTO 2017, Idée Fixe. It’s a great talk. In his casual style he delivers some great insights. The central theme of the talk is “fixed ideas” standing in the way of progress. By becoming fixed on ideas which worked in the past, we lose the openness of mind needed to come up with novel ideas, even when experience or a changing context demonstrate that these old ideas no longer serve us.

Much of last week’s debate has centered on AppCanary’s choice to move back to Ruby, after a bad experience trying to build their platform in Clojure, and so it was a lot of “Clojure vs Ruby”, both on a language level, and on a cultural and philosophical level. I have been doing Ruby since 2006 and Clojure since 2013, I spoke at Ruby and Clojure conferences, and I’m intimately familiar with both of these languages and communities. I have some feels about this, y’all.

Each of these has their most prominent mantra. For Clojure it’s “Simple vs. Easy”, while the Rubyist chant is “Optimized for Programmer Happiness”. What do these mean, really? And what are the blind spots, the things we are simply unable to see, because these fixed ideas are in the way?

Simple vs. Easy

At Strange Loop 2011 Rich Hickey delivered one of his classic talks, Simple Made Easy, which would have a lasting effect on the discourse around Clojure. In it he contrasts “simple” with “easy”. Simple is the opposite of complex, it is a measure of how entangled things are, of how much is folded and twisted into one. Simple software is focused, it does not interleave multiple concerns.

Easy is the opposite of hard, it is a measure of the effort required to perform a task. This is largely subjective, something we are familiar with requires less effort, and so is perceived as easy.

When the selling point of a framework is that you can “build a blog in 15 minutes”, or that a DSL “reads like English”, then you’re talking about ease. Ease helps us when initially writing code. It lets us move fast, and that is not undesirable.

In the longer run other aspects come to the foreground. Why is it that, as projects age, the speed of development tends to slow down? That it becomes harder to make changes? How do you build something non-trivial over time, while remaining confident in its quality and correctness?

For that you need to be able to reason about the system. Human minds can only juggle so many things at the same time, and because of this simplicity reigns supreme. We can become familiar with hard things and thus make them easy, but dealing with complexity will continue to hurt your brain. Years of practice won’t change that.

And so Rich’s assertion is that many balls of mud sprang from a focus on ease, while sweeping complexity under the mat. And so he decided to build a language based on those features that promote simplicity, and rejecting those that lead to complexity.

Mutable state intertwines everything it touches. Objects mix functionality and state. Variables add a dimension of time to any code that references them.

Contrast that with immutable values, which are always local in time and space; pure functions, which can be reasoned about in isolation; reference types which make the dimension of time explicit by separating values from identities.

Clojure is not designed to be hard, to the contrary, I think a lot of thought has gone into making it easy to use as well, but when ease and simplicity are at odds, then simplicity always wins.

Programmer Happiness

Ruby’s creator, Yukihiro Matsumoto (Matz for short), has stated repeatedly that Ruby is designed to make programmers happy.

The goal of Ruby is to make programmers happy. I started out to make a programming language that would make me happy, and as a side effect it’s made many, many programmers happy.

He doesn’t really spell out what those things are that make him happy, but we can gather some insight by looking at what he borrowed from other languages, and what he left out. What may surprise you is that, before creating Ruby, Matz’s primary language was Lisp. Perl and Python are also cited as major influences. He wanted to build a modern object oriented scripting language, more suitable for building large systems than Perl, which he considered a toy language, and more pervasively object-oriented than Python, and so he borrowed the object model from Smalltalk.

When it comes to modeling software Ruby comes closest to Smalltalk, while syntactically, Ruby feels more like Perl, once the favorite scripting language of hackers and tinkerers the world over. Perl is the brainchild of Larry Wall, by education a linguist. Perl is heavily inspired by natural language, it championed the idea that programming languages should be designed for the human doing the programming, not for the machine running the program. In his talk Perl, the first postmodern computer language, Larry says,

So, to drag the subject back to computers, one of the characteristics of a postmodern computer language is that it puts the focus not so much onto the problem to be solved, but rather onto the person trying to solve the problem. I claim that Perl does that, and I also claim that, on some level or other, it was the first computer language to do that.

Much of that talk goes into the contrast of a reductionist Modernism vs a more holistic postmodernism, it’s a fascinating read, I highly recommend it.

Modernism, as a form of Classicalism, was always striving for simplicity, and was therefore essentially reductionistic. That is, it tended to take things to pieces. That actually hasn’t changed much. It’s just that Modernism tended to take one of the pieces in isolation and glorify it, while postmodernism tries to show you all the pieces at once, and how they relate to each other.

This still hasn’t given us a clear sense of what is meant with “programmer happiness”, but I’ll venture that it has to do with approaching things in a natural, organic way. Designing a language that appeals to the analytic and the creative and emotional brain equally. A language that loosens the straightjacket and lets you express yourself freely. Ruby promotes humane interfaces

The essence of the humane interface is to find out what people want to do and design the interface so that it’s really easy to do the common case.

Even when picking up a library for the first time you can often guess method names without looking at the docs. It just “does what you would expect”. Some even add aliases. Would you like some is_a? or do you prefer instance_of?? It doesn’t matter, they do the exact same thing!

Fixed ideas

Is there any surprise that these two sides seem to be speaking past each other? It’s like they live in different worlds. How can a Clojurist wearing their “Simple vs Easy” sunglasses ever comprehend the joy of creation sparking in the heart of a Rubyist? And how do we explain to the Ruby programmer the beauty of functional code, of having code and data laid bare, nothing up the sleeve, nothing tucked under the covers, just plain values, endlessly flowing, when all they can see is boilerplate code and single letter variable names?

And yet each side has much to learn from the other, once we get past our fixed ideas.

“Simple Made Easy” has instilled in many minds the notion that simple and easy are two sides of a spectrum, that they are necessarily at odds. But simple/complex and easy/hard are separate dimensions. While there’s great merit in striving for simplicity, it would be a mistake to disregard ease. I think as Clojure programmers, as library authors, we have been too focused on the reductionist, on building solid parts. But it’s only when these parts come together and meet the real world that magic happens.

The real world is messy, it’s a complex tangle, a braiding of concerns and constraints. Dealing with that is why we are programmers, this is the real measure of our worth. At the heart of our systems we must strive for “simple”, but at the edges we must inspire, delight, make the impossible effortless. We must do this for our customers, and we must do this for our peers.

Every tool, every library forms an interface, a language that people must first master to convey their intent. Pay as much attention to designing these interfaces as you would designing their functional internals. This is the face with which your code looks upon the world. Make it smile with its eyes.

To quote Laozi,

People usually fail when they are on the verge of success.
So give as much care to the end as to the beginning;
Then there will be no failure.

And Rubyists, you too have something to gain from this exchange. Yes, you’ve been hearing for years of the benefits of immutable data, the elegance of pure functions. These are interesting ideas, but don’t just read about them, try them out, use them in anger, and pay attention to how this influences the resulting system. You can do this in Ruby, but it will be hard to break out of old habits, so instead I recommend picking up a simpler, functional language, Clojure, OCaml, Elixir, and putting it through its paces. Afterwards you’ll look at your Ruby projects with fresh eyes, and a new sense of where complexity comes from.

I’ll leave you with one more data point to ponder: Clojure has polymorphism, but it eschews concrete derivation. It has interfaces and protocols, but no inheritance chains. It’s not a design decision that gets put in the limelight much, but it is one I encourage you to study. This alone has tremendous impact on how maintainable systems are.

MINSWAN

One interesting thing that surfaced in the debates is that while some describe the Clojure community as “incredibly friendly and helpful”, others describe it as hostile. Well, which one is it? Again I think it’s interesting to compare and contrast with the Ruby community.

From my experience, the average interaction on Clojure’s Slack, mailing lists or Github issues is polite and friendly. I see people tirelessly and patiently answering questions in the #beginners channel and elsewhere. People really want to help.

And yet it’s a very different vibe from what I see in the Ruby world. There people really go out of their way to be nice to each other. Github issues are accompanied by a bit more elaborate explanations, some emoji or animated gifs, because it’s a low bandwith medium and you really want to make sure the human on the other side doesn’t take things the wrong way. A phrase that was popular in the early days was “MINSWAN”, “Matz is Nice So We Are Nice”. It’s something that deeply permeates this community, it’s part of what made Rails Girls such a huge success, and it’s why I still love going to Ruby conferences. It’s a vibe that’s hard to beat.

There are trolls in Rubyland too, but they get called out immediately. There is very little tolerance for less than friendly behavior. Virtually every conference and meetup has, and enforces, a Code of Conduct. Being welcoming, especially to beginners, is an essential part of Ruby’s DNA. How to be and remain open and welcoming is an important part of the discourse.

Clojure is different, it’s a mixed bunch. There are old-school lispers, converted Java programmers, people coming from other dynlangs like Ruby or Python, and they all carry different expectations. If you’ve been active in open source for more than a decade you know that a thick skin was a basic requirement. Harsh interactions were par for the course. People do what they are used to, and without a guiding principle like MINSWAN it’s harder to call people out and hold everyone to higher standards.

In the Clojure world, as in Clojure code, brevity is considered a feature, but there’s a thin line between being concise, and being curt. People still try to be friendly and nice, but the dial isn’t turned up all the way to 11. This is painfully true when it comes to the official docs, which seem to be written for machines rather than humans, it shows in the error messages, and it shows in many small online interactions.

Languages that draw a younger, more homogeneous crowd: Elm, Elixir, JavaScript, seem to be better at prioritizing the humanistic aspect. Both in the affordances of the software (Elm’s famous error messages), and in person-to-person interactions. I think we can, and should, take a leaf out of their book.

Catering for the Novice

People cite many pain points when coming to Clojure. Chas Emerick summarized it well:

✅ jvm pain
✅ docs/error msgs
✅ deployment pain
✅ tooling/debugging pain
✅ domain modeling difficulty

There’s truth in all of these, and we as a community will have to stand up if we want to change these, but I want to focus on one more thing in particular: meeting the needs of the absolute beginner.

The Dreyfus model distinguishes five levels of competence, from novice to mastery. At the absolute beginner level people execute tasks based on “rigid adherence to taught rules or plans”. Beginners need recipes. They don’t need a list of parts, or a dozen different ways to do the same thing. Instead what works are step by step instructions that they can internalize. As they practice them over time they learn the reasoning behind them, and learn to deviate from them and improvise, but they first need to feel like they’re doing something.

I have taught many people Ruby on Rails. Rails is tremendously complex (and complected), but it gets this part right. In a few sessions you can teach a person to create an interactive website backed by a database. It’s frustrating to teach because you’re walking a tight rope. Just follow the steps. Don’t peek under the covers. Don’t stare into the abyss. But that feeling of instantly being productive is what draws people in, what makes them think, “hey, maybe I can do this”.

People criticize this as optimizing the wrong thing. Yes, initial prototyping goes really fast, but long term maintainability suffers. This criticism isn’t without merit, but it tends to overlook this important aspect. “The Rails Way” provides a framework that makes teaching easy. It means you can just dive in and ignore all the peripheral stuff until later.

For ClojureBridge we tend to teach graphics programming with Quil, with Nightcode as the editor. There the experience is similar. Within the first hour people are doing stuff, they’re building things. And there are plenty of recipes out there for Quil that people can adopt and run with.

But in general, and for web development in particular, Clojure fails to deliver that experience. This may sound like a case for more of a “framework” and less of a “library” approach, but I think the bigger issue is documentation. We need more practical tutorials and how-to guides, that provide clear recommendations of tools and libraries to use, that explain things step by step, with empathy, with beginners in mind. Guides that you can follow from top to bottom and that actually work, even when you’re on Windows, or Linux, or have never heard of a classpath.

We’re also missing a dialogue about how to program, both in the small: how do you structure a function, what are common idioms, how do you manipulate data structures; and in the large: doing domain modeling, architecting systems, designing interfaces. Ruby folks talk about these things all the time, but talks like these are eerily absent from Clojure conferences, and yet it’s something people consistently cite as a stumbling block.

If we want Clojure to continue to grow, we need to take responsibility for how it is perceived. Clojure is not always perceived as a friendly language. We can retort, “it was very friendly to me”, or we can listen without interrupting the speaker, believe they are speaking from good faith, and do better.

🡅 You can comment (and upvote) on Reddit.com


Update: The https://clojure.org web site has a guide section for tutorials and guides and accepts pull requests.

Many thanks to Chas Emerick, Eric Normand, and Tobias Pfeiffer for reviewing an earlier version of this article.

Permalink

Should Cognitect do More for Clojure?

Poor open-source development practices, neglect for the beginner experience, and lack of communication have come up as complaints against how Cognitect stewards Clojure. I address the complaints with a plea that we do more as a community.

Read full post

Permalink

Notes on Debugging Clojure Code

Clojure is a great programming language, but a recurring complaint I keep hearing from developers hacking on Clojure code is that debugging can be unpleasant. First of all, I agree! Debugging Clojure code can be more daunting on average than, say, debugging Python code. This is mainly due to two reasons:

  1. Clojure's Java legacy. Clojure is compiled to Java bytecode, which has some terminology and idiosyncracies Clojure programmers aren't always familiar with. These terms tend to pop up in stack traces and cause confusion (e.g. IFN).
  2. Clojure — being a Lisp — has a certain code structure which is different from, say, a more common imperative coding style. Rather than being a sequence of statements, Clojure programs tend to involve long call chains of nested expressions. Where only part of an expression fails, it's often non-trivial to figure out why.

In this post, I want to share some notes from my own experience debugging Clojure programs.

Permalink

Do you really need immutable data?

Immutable state has been all the rage for the past few years or decades. The multithreaded multiprocessing future is coming! Save yourselves and your sanity, use immutable data! Be functional! Object-oriented is for dinosaurs. hair on fire

This push has been particularly strong and revered in JavaScript land. Everyone got tired of messing around with jQuery, so now we’re doing immutable everything with fancy-pants unidirectional architectures.

I’m not saying that’s a bad thing. It’s a great thing.

I’ve been on the functional hype train ever since I played around with Haskell and Clojure back in college. Some 6 or 7 years ago. 😳

Even I switched to JavaScript after I realized that at its heart, JavaScript is a neat functional language. And literally everyone has a VM for it.

So why immutable data?

Immutable data purports to solve all your problems. You take an object or string or number or whatever, and you don’t change it to make a change. Oh no, you make a copy and change that. Or rather, you make a copy with changes and you pretend that was an atomic operation.

The issue you’re trying to solve is this:

Another few hours of debugging time wasted because an object was being shared somewhere and then mutated causing side effects elsewhere

~ Jani Hartikainen

Time wasted because when state changed over here, stuff wiggled and moved over yonder. We don’t want that. The bigger your application, the harder it gets to understand what’s going on.

Wouldn’t want to have side effects, would we?

But here’s the thing: you’re using a Von Neumann machine. There are always side-effects. State is always mutable. At the very end of the day, under all your layers of abstraction, you have memory. Memory is a series of bytes, and if you want things to happen, those bytes have to change.

You can copy state all you want, but at some point you’re going to run out of memory and you will have to start changing things. That’s a fact of life unless you’re very fortunate and have infinite storage and infinite memory somehow. In that case, you’re probably Google or Amazon. Lucky bastard.

And I’m sure even Google or Amazon don’t keep copies of useless old objects lying around. They’re the kind of people who remove the closing </html> tag from their homepages to save a few terabytes of bandwidth per day.

It’s not an issue of mutability; it’s an issue of how you think about your application.

Why we think immutability helps

I think immutability is a head fake. It forces you to think about how you structure your application.

Look at something like a sum operation. Done the old way, it looks something like this:

let sum = 0;
for (let i = 0; i < arr.length; i++) {
    sum += arr[i]
}

You take a piece of memory, set it to 0, then walk through an array of memory locations, and add them to your original piece of memory. That memory spot keeps changing.

This is a hairy situation because another thread might change that same spot of memory. If that happens, your result could be incorrect.

We can fix that with a functional/immutable approach, like this:

let sum = arr.reduce((sum, n) => sum+n, 0)

Walk through the array of memory locations, but with a function call each time. Each function gets the previous sum and the new n and returns the next sum. When we're done, we put it in the new sum memory location.

The function call stack ensures that we never re-used a memory location. We are therefore safe from tampering from other threads.

Great. Very useful in multi-threaded programming.

Guess what isn't multithreaded, though. JavaScript. 😁

Unless you're dealing with LocalStorage or web workers, JavaScript can never suffer from problems of multiple threads and shared state. At least not in the way that more traditional runtime environments might.

Sure, you have asynchronous code, and if you're not careful, that's going to mess you up. That same .reduce() call above is resilient against asynchronousness, the for approach is not.

But the real trick isn't that we used an immutable approach and that was magically better. The trick is that we changed how we think of summing numbers.

We changed sum into the final stage of a state machine. Our result was no longer an expression of state and some steps, but a pure expression of state.

Good apps are state machines

You can think of our sum example above as constructing a custom state machine for just that array in particular. It contains as many states as there are elements in the array. Each state knows the current total sum. The final state knows the entire sum.

This is where a picture would help.

In this particular state machine, transitions only go in one direction. With bigger apps, it gets hairier. States can transition in many ways, and the states themselves are more complex, too.

But if you think of your whole application as a state machine, where everything is a pure expression of state, then immutability stops being a problem.

Once state changes, you want that change to reflect everywhere. If I press "Play" on Spotify, I want my whole phone to react. iTunes has to stop playing, the music dock thingy has to update its UI, my headphones have to make sound, things like that.

The state of my whole device, an entire OS and all its apps, is an expression of the state of playing music.

If one of the things you expect to change doesn't change, say a Youtube video keeps playing while you're listening to music, that would be a bug. You'd hate that.

Why then are we so afraid of side effects in our own apps? Users want the entire app to work together in unison.

Just remember how annoying it was when you replied to a message on your phone, but the Facebook website still showed notifications. They've fixed that.

Or when you reply to a comment on a post, but the widget still says you have new comments. Annoying.

Users want side effects. Users need side effects.

Embrace them. Your app should be a state machine where everything is an expression of state. Your logic should manipulate the state and your app should react.

Problems start when you break that promise.

The post Do you really need immutable data? appeared first on A geek with a hat.

Permalink

Readable Clojure

This is how you can make Clojure code more pleasant to work with.

Don’t use “use”

And don’t :refer anything either. Every var you bring from another namespace should have a namespace qualifier. Makes it easier to track vars to their source.

You’ll also save yourself from name collisions down the way.

Use consistent, unique namespace aliases

If you gave namespace an alias, stick to it. Don’t require

[clojure.string :as str]

in one file but

[clojure.string :as string]

in another.

That way you’ll be able to actually remember your aliases. Oh, and grep starts to work.

Keep aliases unique too. If d/entity could mean both datomic.api/entity or datascript.core/entity, you lose all the benefits of this rule.

Use long namespace aliases

Aliases should be readable on their own. Therefore

  • don’t use single-letter aliases,
  • don’t be clever or inventive,
  • when shortening, only remove the most obvious parts (company prefix, project name, clojure.*, core suffix etc),
  • leave everything else intact:

Now you can read your code starting from any place and don’t have to remember what maps to what. Compare

with

The former looks terser, but it’s hard to tell what’s going on. The latter is a bit longer but immediately communicates which systems are in play.

Another benefit: you’ll naturally tend to use aliases less often if they are long and clumsy, so long aliases will force you to organize your code better.

Choose readability over compactness

Clojure has a plethora of ways to write dense code. Don’t use them just because they are there. Always put readability and code clarity first. Sometimes it means even going against Clojure idioms.

An example. To understand this piece of code you need to know that possible-states is a set:

By contrast, to understand following code you don’t need any context:

Also, notice how the latter reads almost like plain English.

My (incomplete) set of personal rules:

  • use contains? instead of using sets as functions,
  • use get instead of using map as a function,
  • prefer (not (empty? coll)) over (seq coll),
  • explicitly check for nil?/some? (more on that below).

Don’t rely on implicit nil-to-false coercion

Unfortunately, Clojure mixes two very different domains: nil/existence checking and boolean operations. As a result, you have to constantly guess author’s intents because they’re not expressed explicitly in the code.

I advise using real boolean expressions and predicates in all boolean contexts. Explicit checks are easier to read and communicate intent better. Compare implicit

and explicit

The more serious reason is that nil-as-false idiom fails when you want false to be a possible value.

Problems like this are common when working with boolean attributes/parameters and default values.

Some advice to follow:

  • wrap plain objects with some? in when/if,
  • prefer when-some/if-some over when-let/if-let,
  • be careful with or when choosing a first non-nil value,
  • for filter/remove predicates, provide proper boolean values through some?/nil?.

Avoid higher-order functions

I found code that builds functions with comp, partial, complement, every-pred, some-fn to be hard to read. Mainly because it looks different from the normal function calls: no parens, application order is different, you can’t see arguments.

It requires effort to figure out what exactly will happen:

Even as experienced Clojure programmer I haven’t developed a skill to parse such structures easily.

What I find easy to read, though, is anonymous function syntax. It looks exactly like a normal function call, you can see where parameters go, what’s applied after what — it’s instantly familiar:

Don’t spare names

Some facilities in Clojure (threading macros, anonymous functions, destructuring, higher-order functions) were designed to let you skip names:

This is great but sometimes impedes readability. Without names, you are forced to keep all the intermediate results in your head.

To avoid that, add meaningful names where they could be omitted:

You can omit names in threading macros (->, ->> etc) but only if object/objects passed through do not change their type. Most cases of filtering, removing, modifying elements in a collection are fine.

E.g. here because it’s still users all the way until the end, intermediate names can be omitted:

Don’t use first/second/nth to unpack tuples

Although this works:

you’re missing an opportunity to use destructuring to

  • improve readability,
  • assign names to tuple elements
  • and show the shape of the data:

Don’t fall for expanded opts

The expanded opts idiom does only two things:

  • it is extremely cool,
  • and it saves you two curly brackets at the call site.

The downsides are much more serious. start will be extremely painful to call if you construct map of options dynamically or if you need to do it through apply:

Because of that, I recommend to always accept options as a map:

Use * as prefix for references

References and their content are different, so they need different names. At the same time, they are not that different to invent unique combination of names each time.

I suggest simple convention: prepend * (star) to reference names.

The star was chosen because it resembles C/C++ pointers.

Align let bindings in two columns

Compare this:

to this:

I do it by hand, which I consider to be a small price for readability boost that big. I hope your autoformatter can live with that.

Use two empty lines between top-level forms

Put two empty lines between functions. It’ll give them more space to breathe.

Seems unimportant, but trust me: once you try it, you’ll never want to go back.

Permalink

The REPL

The REPL

Integrity, Kotlin love, and Frankenstein
View this email in your browser

The REPL

-main

  • James Reeves continues Advancing Duct
  • Robert Herrmann has created a directory of Clojure consultants. He's also available for hire himself.
  • The videos from clojureD 2017 are up.
  • David Nolan - Idée Fixe at GOTO Chicago 2017.
  • A big discussion on Reddit about Clojure's future growth

Libraries & Books.

  • re-frankenstein is a deviant fork (their words!) of re-frame. It allows you to run re-frame without global state. I've been thinking about this a lot, so it's helpful to see some other ideas.
  • Towards Cortex 1.0 (a machine learning toolkit in Clojure)
  • You can now use Specter paths with EDN via specter-edn
  • CUDA matrices in Clojure with Neanderthal

People are worried about Types. ?

But they're staying quiet this week.

Foundations.

Tools.

Recent Developments.

  • Alex Miller has requested comments for var printing, relating to serialisation support for vars in EDN.
  • Thomas Heller has a new take on ClojureScript and npm
  • CLJ-2075: unroll comparisons to include three arity versions

Learning.

  • Cognitect have a bunch of useful articles about Datomic usage on their support site.
  • ClojuTRE 2017 is open for ticket sales and an RFP

Misc.

  • I transcribed Bryan Cantrill talking about integrity at GOTO. I'd strongly encourage you to read it and listen to the whole discussion.
Copyright © 2017 Daniel Compton, All rights reserved.


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list

Email Marketing Powered by MailChimp

Permalink

PurelyFunctional.tv Newsletter 226: Hacking+Ruby+Clojure

Issue 226 – May 22, 2017

Hi Clojurers,

Thanks to everyone who responded to my plea last week. I have really great readers with great insights.

I got some optimistic perspectives and some were rather pessimistic. I just wanted to reassure everyone that I do have healthy revenue growth on my videos and I do plan on continuing helping people learn Clojure. If anything, I’ve got a more realistic view of the community and a lot of motivation to improve it. We’re not bad off and there’s plenty of room for growth.

Rock on!
Eric Normand <eric@purelyfunctional.tv>

PS Want to get this in your email? Subscribe!


To Clojure and back: writing and rewriting in Ruby YouTube

I learned about this conference talk this week. It is excellent. Everything Phill MV talks about makes total sense. The thing that is most painful to me is that the phrase “user hostile” rang true with his Clojure experience. We need to listen to these experiences. They may not be totally true in general, but for every Clojure failure story we hear, there must be a hundred we don’t.

An unfortunate thing happened after the talk was published. Apparently the video drew a lot of abuse. This is not okay. He shared his personal experience and there’s no reason to get defensive about it. Please, please, be more excellent to each other.


Emacs and Clojure, a Lispy Love Affair YouTube

Arne Brasseur totally shares his screen while rocking Emacs.


Bounce! Hacking Jazzfest with Social Videos

A couple of weeks ago I participated in a hackathon. I love hackathons if they’re done right. They remind me of the joy of programming and creation.


Ruby versus the Titans of FP YouTube

Cassandra Cruz loved Functional Programming and tried to make it great in Ruby. Her talk is a great lesson on some of the tougher concepts in FP: higher order functions, function composition, and currying.


Who’s using Clojure, and to do what?

A recent, partial list of companies using Clojure. I was surprised by the quantity and variety. Does your company use Clojure? Put it on this page. Also, want to get more productive? Email me about training.

Permalink

Copyright © 2009, Planet Clojure. No rights reserved.
Planet Clojure is maintained by Baishamapayan Ghose.
Clojure and the Clojure logo are Copyright © 2008-2009, Rich Hickey.
Theme by Brajeshwar.