In Clojure, if you want a basic OOP behavior without killing yourself to fully implement Java classes and interfaces in Clojure, the preferred technique is to use records. Sometimes implementing protocols in records suits your needs, mostly due to speed of code execution. However, if you want polymorphism with your records, then multimethods are where it’s at.
Admittedly, multimethods are very flexible, so the technique I’ll show you is one of many techniques you could use. The basic pattern I use for inheritance with records, is to use the
derive command with keywords that are kept as a value in the record. For example,
(defrecord food [
(defn construct-food [name color yummy]
(->food ::food name color yummy))
(derive ::fruit ::food)
(defrecord fruit [
(defn construct-fruit [name color yummy needs-peeling]
(->fruit ::fruit name color yummy needs-peeling))
type is used to track
isa relationships of
derive is used to set
::food as the parent of
::fruit . Notice the use of custom constructors to set default values for
type in the records.
Continue reading “Clojure Record Heirarchy”
Most of the time, Clojure does not need locks like Java and other languages. This is because of
ref s, and
agent s. I’ll focus on Clojure agents in this short post.
Agents are handled in single-threaded queues. By lining up calls of a function in a queue, no locks are needed. When combined with
send-off , deadlocks won’t happen.
Here’s a quick example.
(def x (agent 0))
(println "Starting send-offs for agent")
(dotimes [_ 10]
(send-off x mod-x)
(println "x is now" @x))
(println "final value ... " @x)
A few things are going on here, so let’s look at them.
Continue reading “Clojure Agents”
Want some Object Oriented Programming in Clojure? Here’s a quick example.
Let’s create a dog object.
"Just a protocol"
(barking [this] "bark")
(hungry [this] "hangry")
(defrecord Dog [breed ^Integer age color]
(barking [this] (str "barking my breed ... " (:breed this)))
(hungry [this] (str "I'm so hungry I could age one whole year to ... " (str (inc (:age this)))))
(sleeping [this] (str "Really tired, and it has nothing to do with my fur color that is " (:color this)))
Now let’s use the dog object.
[temp2020toss.dogo :refer :all])
(:import (temp2020toss.dogo Dog)))
"I don't do a whole lot ... yet."
(println "Hello, World!")
(let [my-dog (Dog. "chow" 8 "green")]
(println "-->" (:breed my-dog))
(println "-->" (barking my-dog))))
See, OOP in Clojure is fairly simple. This sample uses protocols with records, but you can add polymorphism with just a little extra work. For polymorphism, use records and multimethods.
I absolutely love the user razvan’s Clojure
defrecord example over at stackoverflow, so I copied it here. I know I’ll never find it again if I don’t. Look at the original over on stackoverflow at this link.
Here’s the example …
Clojure defrecord example:
;;define Address record
(defrecord Address [city state])
;;define Person record
(defrecord Person [firstname lastname ^Address address])
;;buid the constructor
(defn make-person ([fname lname city state]
(->Person fname lname (->Address city state))))
;;create a person
(def person1 (make-person "John" "Doe" "LA" "CA"))
(:city (:address person1))
If you’re looking for more information on combining protocols with records in Clojure, then Matthew Boston has the blog for you!
NOTE: All the code in this tutorial can be quickly tested at the REPL using the command
lein repl to start a REPL to test with.
One of the first things you learn when learning clojure is
println . For example,
That’s probably the first Clojure program you ever wrote. Maybe you wrote this variation.
print are the first ways learned of displaying output in Clojure, most Clojure developers continue using them when debugging code. Nothing wrong with that. But sometimes it is better to use a more specialized tool.
In steps the
pr commands. These two commands are tailored for printing objects. At first glance, they appear to work the same as
println . However, they actually show more information in some instances.
println , the
\n in the following code quietly gets replaced by the action of a new line being printed.
prn are used, the two characters
n are displayed instead of an actual new line. This is very handy when hidden characters are fowling up your layout, or needed to be visible when debugging code.
Final note: The only difference between
prn , is that
prn prints a new line after the objects it is printing out.
Migratus is a wonderful migration tool for Clojure. You can use it on its own, or if you have a Luminus project, it is already included.
There are a few areas that could use some extra tutorials, though. One of them is code-based migrations. Especially, examples on how to modify the database would be nice.
Here’s a quick explanation of how to modify the database with a code-based migration in Migratus.
First, create an *.edn file in the folder with the regular migrations. It takes the same format as other migrations, so you can really just change the extension of one of your created migrations to ‘.edn’ and change the contents.
Continue reading “Code-based Migrations with Migratus in Clojure”
You can save a lot of time, money, and frustration by using prewritten libraries and tools when making your full stack apps. One such tool is Redis. Redis is a server that works on most platforms for server-side caching, pub/sub, messaging, Lua scripting, and data structure storage. It is thread-safe, loves puppies and is good with small children.
Seriously, even if you just use Redis as your cache, you’ll save a lot of frustration and make your app scalable.
This tutorial gives an example of using Redis for pub/sub, also known as Publish/Subscribe. All this will be done using Clojure’s Carmine library. (Additional documentation for Carmine found here.
Continue reading “Clojure Redis Pub/Sub with Carmine”
Once you learn Clojure (or any programming language) well enough to tackle a large project, you are going to run into lifecycle, dependency, and state management issues.
Two great resources for handling lifecycles, dependency, and state in Clojure apps are Mount and Component. I use Mount for my projects, but both are popular solutions. This post is about tolitius/Mount.
Simple Mount Example
Continue reading “Clojure Mount”
Yes, you can write Java Servlets in Clojure.
Create a Clojure Servlet project with the following command.
lein new luminus my-clj-servlet +war
The important parts of the command are ‘luminus’, which is the framework used to create the Servlet, and ‘+war’, which adds uberwar and Servlet routes to the project. This creates a file called ‘handler.clj’ that replaces the traditional Java Servlet file. The configurations for the Clojure Servlet are found in ‘project.clj’ in the
:uberwar section of the configurations.
By default the lein command above creates a project that will build a WAR file called my-clj-servlet.war, and when deployed will deploy in the my-clj-servlet context, meaning on a default installation of Tomcat you would find the link at http://localhost:8080/my-clj-servlet/
It is important to note that the resulting project from the above lein command actually won’t work as a Servlet, yet. But, we’ll fix that below. The project is configured in the hopes that you can run it from a Servlet container or as a standalone app, and with some massaging, you could. However, this tutorial only focuses on how to get the project compiling as a Java Servlet written in Clojure. If there is enough interest, I’ll write another tutorial on how to get the default project working as a standalone app, and a Servlet.
Continue reading “Java Servlets Written in Clojure”
As mentioned in my other post about plaintext emails, I recommend using the Apache Commons Email library when sending email from Clojure apps. First up, you need to add the dependency to ‘project.clj’
Next, your HTML email has both an HTML version and the alternative plaintext version of the email. Notice, all you have to do is create an instance of HtmlEmail and then call the set and send methods on it using ‘doto’. Pretty easy.
(:import (org.apache.commons.mail HtmlEmail)))
"I don't do a whole lot ... yet."
(println "Email the World ...")
(let [smtp-address "smtp.example.com"
subject "Test email"
msg-html "<html>This is your basic html text email.<br>Enjoy!</html>"
msg-plain "This is your basic alternate plain text email.\nEnjoy!"]
(println "... Email Sent!"))
There are more examples and the javadocs over at the Apache Commons site. However, this should be a basic enough example to get you started.