Reader small image

You're reading from  The Clojure Workshop

Product typeBook
Published inJan 2020
Reading LevelBeginner
PublisherPackt
ISBN-139781838825485
Edition1st Edition
Languages
Right arrow
Authors (5):
Joseph Fahey
Joseph Fahey
author image
Joseph Fahey

Joseph Fahey has been a developer for nearly two decades. He got his start in the Digital Humanities in the early 2000s. Ever since then, he has been trying to hone his skills and expand his inventory of techniques. This lead him to Common Lisp and then to Clojure when it was first introduced. As an independent developer, Joseph was able to quickly start using Clojure professionally. These days, Joseph gets to write Clojure for his day job at Empear AB.
Read more about Joseph Fahey

Thomas Haratyk
Thomas Haratyk
author image
Thomas Haratyk

Thomas Haratyk graduated from Lille University of Science and Technology and has been a professional programmer for nine years. After studying computer science and starting his career in France, he is now working as a consultant in London, helping start-ups develop their products and scale their platforms with Clojure, Ruby, and modern JavaScript.
Read more about Thomas Haratyk

Scott McCaughie
Scott McCaughie
author image
Scott McCaughie

Scott McCaughie lives near Glasgow, Scotland where he works as a senior Clojure developer for Previse, a Fintech startup aiming to solve the problem of slow payments in the B2B space. Having graduated from Heriot-Watt University, his first 6 years were spent building out Risk and PnL systems for JP Morgan. A fortuitous offer of a role learning and writing Clojure came up and he jumped at the chance. 5 years of coding later and it's the best career decision he's made. In his spare time, Scott is an avid reader, enjoys behavioral psychology and financial independence podcasts, and keeps fit by commuting by bike, running, climbing, hill walking, snowboarding. You get the picture!
Read more about Scott McCaughie

Yehonathan Sharvit
Yehonathan Sharvit
author image
Yehonathan Sharvit

Yehonathan Sharvit has been a software developer since 2001. He discovered functional programming in 2009. It has profoundly changed his view of programming and his coding style. He loves to share his discoveries and his expertise. He has been giving courses on Clojure and JavaScript since 2016. He holds a master's degree in Mathematics.
Read more about Yehonathan Sharvit

Konrad Szydlo
Konrad Szydlo
author image
Konrad Szydlo

Konrad Szydlo is a psychology and computing graduate from Bournemouth University. He has worked with Clojure for the last 8 years. Since January 2016, he has worked as a software engineer and team leader at Retailic, responsible for building a website for the biggest royalty program in Poland. Prior to this, he worked as a developer with Sky, developing e-commerce and sports applications, where he used Ruby, Java, and PHP. He is also listed in the Top 75 Datomic developers on GitHub.
Read more about Konrad Szydlo

View More author details
Right arrow

9. Host Platform Interoperability with Java and JavaScript

Overview

In this chapter, we will look at interoperability between Clojure and both Java and JavaScript. Clojure runs on top of platforms provided by Java and JavaScript. Clojure was designed to use libraries provided by Java or JavaScript. We will learn how to access Java and JavaScript objects and methods in Clojure. We will also learn how to convert data between Clojure and Java or JavaScript and back. After learning how to access Java and JavaScript from Clojure, we will investigate how to perform Input-Output (I/O) operations like reading and writing to files using Java classes. We will then learn how to deal with errors and exceptions in our code.

By the end of this chapter, you will be able to work with the appropriate syntax and semantics to access Java and JavaScript objects and methods from Clojure, and deal with Java exceptions and JavaScript errors.

Introduction

In the previous chapter, we learned how to create a Leiningen project. A project gives a structure for organizing our code. We structure our project around namespaces. We created new namespaces and we imported external Clojure libraries in order to use them in our code.

Now that you are familiar with using namespaces and creating Clojure projects, it is time to become more comfortable with working on projects that use Java and JavaScript.

As we learned in Chapter 1, Hello REPL!, Clojure compiles to Java bytecode and operates on the Java Virtual Machine (JVM). The JVM is a host platform. Any programming language that compiles to Java bytecode can run on the JVM. Because Clojure compiles to Java bytecode and runs on the JVM, we call it a hosted language. Java dates from the 1990s and is now one of the most popular backend languages. We can leverage existing Java libraries instead of writing a lot of code on our own. This helps us deliver new features faster.

As...

Using Java in Clojure

Any code written by a developer needs to be converted to code that is understood by a machine. An interpreter uses code from a developer and compiles it into machine code. Each operating system is different, hence the need for platform-specific compilers and interpreters. One of the reasons why Java is so successful is that it provides the JVM, which takes human-understandable code and converts it into machine code. Developers are not usually interested in the JVM. They can focus on writing code in Java without interacting with the underlying operating system. This job is done by the JVM.

Clojure is a hosted language. It means that it uses the JVM instead of creating a new runtime environment. Clojure cleverly reuses facilities provided by the JVM. This is a very powerful approach. Things such as garbage collection, threading, concurrency, IO operations (all of which will be explained in the following paragraphs) are JVM battle-tested technologies that Clojure...

Working with Java I/O

I/O deals with reading data from a source and writing data to a destination. These are some of the most common activities that programs do. Source and destination are very broad concepts. You could read from a file or a keyboard and display data on a monitor. You could read from a database and write to an API serving data. Java provides classes for many sources and destinations for reading and writing data.

In this topic, we will look at the most common I/O cases:

  • Reading and writing to a file
  • Reading from a keyboard and writing to a monitor

We have already worked with I/O without realizing it. Whenever we start the REPL and type on the keyboard, we perform write operations. Similarly, all function calls in the REPL print to the monitor, performing output operations.

I/O is a huge and difficult topic. Even the people that created Java did not get it right in the beginning, as we can see from the number of classes and packages for I/O....

Using JavaScript in ClojureScript

ClojureScript allows us to use JavaScript constructs. We can call JavaScript methods and functions like any other in ClojureScript. When we called Java from Clojure we used operators such as . dot or \ slash. Using JavaScript in ClojureScript will also require us to learn a new syntax.

While Java operates on classes a lot, in JavaScript we operate on objects. Two JavaScript constructs that we want to use on objects are:

  • Methods
  • Fields

In order to access a method from a JavaScript object, we place . (a dot) followed by a method name. Accessing a field of an object is very similar. We use .- (a dot and a hyphen) before the field name. You might wonder why accessing a function uses slightly different syntax than accessing a field. In JavaScript, an object can have a method and a field with the same name. In ClojureScript, we need a way to distinguish between a function call and a field access.

In JavaScript, the code looks as...

Reactive Web Programming Using Rum

Many websites allow users to interact with web pages. Users can click, drag, and sort elements. These pages are dynamic – they respond to user actions. A programming page that reacts to user interactions is called reactive programming.

HTML provides a structure of elements on a page. The Document Object Model (DOM) is a representation of HTML in JavaScript. JavaScript allows us to operate on DOM elements that are finally displayed as HTML elements on a web page.

One way to make a page react to user actions is to render (display) that whole page again. Rendering a whole page consumes computer resources. If only a small part of the page needs re-rendering, we waste precious resources re-rendering the entire page. Fortunately for us, there is a solution that allows us to re-render only the parts of a page that have changed.

React.js is a JavaScript library that supports reactive programming. The basic block of React.js is a component...

Exceptions and Errors in Clojure

In an ideal world, every program runs without any problems. In the real world, mistakes happen and programs do not run as planned. Errors and exceptions in Java and Clojure are a mechanism for informing developers when such unexpected situations occur.

An error indicates a serious problem that an application should not try to catch or handle. An exception indicates conditions that an application might want to catch. To put it another way, errors are situations from which an application cannot recover. Such conditions could be running out of disk space or memory. If an application runs out of disk space to save data, there is no possibility that this application can serve its purpose. Unless we provide more disk space, the application cannot run successfully. Exceptions are conditions from which an application can recover. Such a condition could be trying to access a list from a database before a connection to the database has been established,...

Errors in JavaScript

In the previous section, we learned about errors and exceptions in Java and how to handle them in Clojure. Unexpected situations that lead to problems in JavaScript applications also happen. This results in a need to handle errors. JavaScript does not distinguish between errors and exceptions, so any situations in which code causes the application not to run as expected are errors.

Like in Java, in JavaScript, we have tools to deal with errors. JavaScript provides four constructs:

  • throw
  • try
  • catch
  • finally

They are the same as we saw in the previous section. JavaScript reuses error handling concepts known from other languages, such as Java. Because JavaScript is not Java, the way we deal with errors in ClojureScript is not 100% the same as in Clojure. It's very close, but code pasted from Clojure to ClojureScript will not work straight away. In the next exercise, we will see how to deal with JavaScript errors in ClojureScript and...

Summary

In this chapter, we have learned about the interoperability of Clojure and Java. We saw how to import Java classes in Clojure. We constructed instances of Java classes and called methods on these instances. We have also learned about macros that help us use Java in Clojure.

Next, we learned about input/output (I/O) operations in Java. We accessed files from a disk, both reading and writing content. We saw how to get input from a user using a keyboard and how to display information back to the user.

After that, we learned about interoperability in ClojureScript. We created a drag and drop application using objects and methods from JavaScript libraries.

Finally, we learned about exceptions and errors in Clojure and ClojureScript. We saw how errors are thrown and how to guard against errors using try-catch blocks. We investigated the finally block and when to use it.

We finished the chapter by working on a help desk application that allows users to sort a list of items...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
The Clojure Workshop
Published in: Jan 2020Publisher: PacktISBN-13: 9781838825485
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Joseph Fahey

Joseph Fahey has been a developer for nearly two decades. He got his start in the Digital Humanities in the early 2000s. Ever since then, he has been trying to hone his skills and expand his inventory of techniques. This lead him to Common Lisp and then to Clojure when it was first introduced. As an independent developer, Joseph was able to quickly start using Clojure professionally. These days, Joseph gets to write Clojure for his day job at Empear AB.
Read more about Joseph Fahey

author image
Thomas Haratyk

Thomas Haratyk graduated from Lille University of Science and Technology and has been a professional programmer for nine years. After studying computer science and starting his career in France, he is now working as a consultant in London, helping start-ups develop their products and scale their platforms with Clojure, Ruby, and modern JavaScript.
Read more about Thomas Haratyk

author image
Scott McCaughie

Scott McCaughie lives near Glasgow, Scotland where he works as a senior Clojure developer for Previse, a Fintech startup aiming to solve the problem of slow payments in the B2B space. Having graduated from Heriot-Watt University, his first 6 years were spent building out Risk and PnL systems for JP Morgan. A fortuitous offer of a role learning and writing Clojure came up and he jumped at the chance. 5 years of coding later and it's the best career decision he's made. In his spare time, Scott is an avid reader, enjoys behavioral psychology and financial independence podcasts, and keeps fit by commuting by bike, running, climbing, hill walking, snowboarding. You get the picture!
Read more about Scott McCaughie

author image
Yehonathan Sharvit

Yehonathan Sharvit has been a software developer since 2001. He discovered functional programming in 2009. It has profoundly changed his view of programming and his coding style. He loves to share his discoveries and his expertise. He has been giving courses on Clojure and JavaScript since 2016. He holds a master's degree in Mathematics.
Read more about Yehonathan Sharvit

author image
Konrad Szydlo

Konrad Szydlo is a psychology and computing graduate from Bournemouth University. He has worked with Clojure for the last 8 years. Since January 2016, he has worked as a software engineer and team leader at Retailic, responsible for building a website for the biggest royalty program in Poland. Prior to this, he worked as a developer with Sky, developing e-commerce and sports applications, where he used Ruby, Java, and PHP. He is also listed in the Top 75 Datomic developers on GitHub.
Read more about Konrad Szydlo