DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Java
  4. Object-oriented Clojure

Object-oriented Clojure

Giorgio Sironi user avatar by
Giorgio Sironi
·
Jan. 10, 12 · Interview
Like (2)
Save
Tweet
Share
12.04K Views

Join the DZone community and get the full member experience.

Join For Free

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]
    Position
        (description    [this]      (str "(x=" x ", y=" y ")"))
        (translateX     [this dx]   (CartesianPoint.    (+ x dx)
                                                        y))
        (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
                                2)))))
(deftest test-point-y-field
    (is (= 2
           (:y (CartesianPoint. 1
                                2)))))
(deftest test-point-to-string
    (is (= "(x=1, y=2)"
           (description (CartesianPoint.    1
                                            2)))))
(deftest test-point-translation-x
    (is (= (CartesianPoint. 11 2)
           (translateX  (CartesianPoint.    1
                                            2)
                        10))))
(deftest test-point-translation-y
    (is (= (CartesianPoint. 1 12)
           (translateY  (CartesianPoint. 1
                                        2)
                        10))))
(deftest test-point-doubling
    (is (= (CartesianPoint. 2 4)
           (doubleCoords (CartesianPoint.   1
                                            2)))))
(deftest test-points-average
    (is (= (CartesianPoint. 3
                            4)
           (average (CartesianPoint. 1
                                     2)
                    (CartesianPoint. 5
                                     6)))))
Clojure

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 5 Best Python Testing Frameworks
  • Chaos Engineering Tutorial: Comprehensive Guide With Best Practices
  • Secure APIs: Best Practices and Measures
  • Multi-Tenant Architecture for a SaaS Application on AWS

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: