Book Image

Clojure Polymorphism

By : Paul Stadig
Book Image

Clojure Polymorphism

By: Paul Stadig

Overview of this book

Clojure is a modern, dynamic language that you can use to develop robust, multithreaded programs. Clojure Polymorphism is a comprehensive guide that shows you how to use Clojure’s features to your advantage. The book begins by describing examples that show how to define and implement abstractions with plain functions and multimethods. Then you'll analyze these examples and separate the good and bad aspects of their design principles. You'll also learn how to perform data transformation abstraction with a plain function and discover how to write new cross-platform predicates while keeping the core of your abstraction free from reader conditionals. The later chapters explain the considerations to keep in mind when implementing Clojure protocols on the Java Virtual Machine (JVM). By the end of this book, you’ll know how to use the various polymorphic tools of Clojure to your advantage while designing your applications.
Table of Contents (7 chapters)

Semantic Gotcha

One of the selling points of protocols is that they are namespaced functions. This mitigates some of the issues of "monkey patching" where someone adds a new function definition to an existing class. In languages where a class is also a namespace, you can run into conflicts if two definitions of a function named get are added to a class at the same time. Since Clojure's protocol functions are namespaced, each person can define their own my.company.project/get and open.source.project/get functions.

However, there is a gotcha. Recall that a protocol also generates a Java interface, and when you extend a protocol in a defrecord, the generated class will implement the protocol's Java interface. Suppose that we defined two protocols:

1 (ns stadig.dog)

2

3 (defprotocol IDog

4   (emote [this]))

1 (ns stadig.cat)

2

3 (defprotocol ICat

4   (emote [this]))

The following code listings do different things:

1 (defrecord CatDog...