Over a million developers have joined DZone.

Object-oriented Clojure

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

Clojure is a LISP dialect, and as such a functional language based on a large set of functions and a small set of data structures that they operate with.

However, it is possible to implement classes and object in Clojure, with constructs well-supported in the language itself. I do not claim you should program in Clojure only with the techniques described in this article: they are just an attempt to bridge Java libraries with Clojure, and to introduce objects and interfaces where needed.

Java interoperability

Even from the Clojure REPL, you can easily instantiate Java classes as long as they are in the classpath (so use lein if they are in a library)
(def ford (Car. arg1 arg2))
Since classes usually reside into packages, in real code you would use their fully qualified name:
(def ford (com.dzone.example.Car. arg1 arg2))
You can also call methods:
(.brake ford arg1 arg2)

The first argument of the evaluation of a .methodName is always the object, while additional arguments are placed after it, in the same s-expression (a fancy name for a list that can be evaluated.)

One of the first exercises in the book The Joy of Clojure is an instantiation of a java.awt.Frame object and a rendering done on it, all from the Clojure interactive interpreter. Doing exploratory testing classes and objects for Java development with the REPL is as faster as writing code into JUnit test.

Define your own: interfaces

defprotocol takes as the first argument an identifier, and a variable number of parameters. Each of this parameters is a method definition like you would do with fn, but without the fn keyword itself and a body to evaluate.

The first argument of the methods should always be this, representing the current object (remember Python?).

(defprotocol Position
    (description  [this])
    (translateX   [this dx])
    (translateY   [this dy])
    (doubleCoords [this])
    (average      [this another]))

Define your own: classes

Defining classes in Clojure is simple, at least when they implement immutable Value Objects. defrecord takes a class name, a list of parameters for the constructor, an optional protocol name and a variable number of arguments representing the methods.

Again, the methods definition are similar to the ones made with fn, but this time with a body, an s-expression to evaluate. There is a catch: you can only implement methods defined in a protocol.

(defrecord CartesianPoint [x y]
        (description    [this]      (str "(x=" x ", y=" y ")"))
        (translateX     [this dx]   (CartesianPoint.    (+ x dx)
        (translateY     [this dy]   (CartesianPoint.    x
                                                        (+ y dy)))
        (doubleCoords   [this]      (CartesianPoint.    (* 2 x)
                                                        (* 2 y)))
        (average        [this another]
                        (let [mean (fn [a b] (/ (+ a b) 2))]
                             (CartesianPoint. (mean x (:x another))
                                              (mean y (:y another))))))

The method access the (immutable) fields of the current object with their names, so this is not probably necessary if not for calling other methods on the object.

Note that records are not strictly objects in the OO sense, since they do not encapsulate their fields: fields can be accessed anywhere with (:fieldname object).

Here's how to work with CartesianPoint objects:

(deftest test-point-x-field
    (is (= 1
           (:x (CartesianPoint. 1
(deftest test-point-y-field
    (is (= 2
           (:y (CartesianPoint. 1
(deftest test-point-to-string
    (is (= "(x=1, y=2)"
           (description (CartesianPoint.    1
(deftest test-point-translation-x
    (is (= (CartesianPoint. 11 2)
           (translateX  (CartesianPoint.    1
(deftest test-point-translation-y
    (is (= (CartesianPoint. 1 12)
           (translateY  (CartesianPoint. 1
(deftest test-point-doubling
    (is (= (CartesianPoint. 2 4)
           (doubleCoords (CartesianPoint.   1
(deftest test-points-average
    (is (= (CartesianPoint. 3
           (average (CartesianPoint. 1
                    (CartesianPoint. 5

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}