Clojure for Java Developers - Eduardo Diaz - E-Book

Clojure for Java Developers E-Book

Eduardo Diaz

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Transition smoothly from Java to the most widely used functional JVM-based language – Clojure

About This Book

  • Write apps for the multithreaded world with Clojure's flavor of functional programming
  • Discover Clojure's features and advantages and use them in your existing projects
  • The book is designed so that you'll be able put to use your existing skills and software knowledge to become a more effective Clojure developer

Who This Book Is For

This book is intended for Java developers, who are looking for a way to expand their skills and understand new paradigms of programming. Whether you know a little bit about functional languages, or you are just getting started, this book will get you up and running with how to use your existing skills in Clojure and functional programming.

What You Will Learn

  • Understand the tools for the Clojure world and how they relate to Java tools and standards (like Maven)
  • Learn about immutable data structures, and what makes them feasible for everyday programming
  • Write simple multi-core programs using Clojure's core concepts, like atoms, agents and refs
  • Understand that in Clojure, code is data, and how to take advantage of that fact by generating and manipulating code with macros
  • Learn how Clojure interacts with Java, how the class loaders work and how to use Clojure from Java or the other way around
  • Discover a new, more flexible meaning of polymorphism and understand that OOP is not the only way to get it

In Detail

We have reached a point where machines are not getting much faster, software projects need to be delivered quickly, and high quality in software is more demanding as ever.

We need to explore new ways of writing software that helps achieve those goals. Clojure offers a new possibility of writing high quality, multi-core software faster than ever, without having to leave your current platform.

Clojure for Java developers aims at unleashing the true potential of the Clojure language to use it in your projects. The book begins with the installation and setup of the Clojure environment before moving on to explore the language in-depth. Get acquainted with its various features such as functional programming, concurrency, etc. with the help of example projects. Additionally, you will also, learn how the tooling works, and how it interacts with the Java environment.

By the end of this book, you will have a firm grip on Clojure and its features, and use them effectively to write more robust programs.

Style and approach

An easy to follow, step-by-step, guide on how to start writing Clojure programs making use of all of its varied features and advantages. As this is a new language, certain new concepts are supported with theoretical section followed by simple projects to help you gain a better understanding and practice of how Clojure works.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 166

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Clojure for Java Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Piracy
Questions
1. Getting Started with Clojure
Getting to know Clojure
Installing Leiningen
Using a REPL
The nREPL protocol
Hello world
REPL utilities and conventions
Creating a new project
Project structure
Creating a standalone app
Using Cursive Clojure
Installing Cursive Clojure
Getting started with Clojure code and data
Lists in Clojure
Operations in Clojure
Functions in Clojure
Clojure's data types
Scalars
Collection data types
Summary
2. Namespaces, Packages, and Tests
Namespaces in Clojure
Packages in Clojure
The classpath and the classloader
Back to Clojure namespaces
Playing with namespaces
Creating a new namespace
Working with namespaces on the REPL
Testing in Clojure
Testing from the command line
Testing in IntelliJ
Summary
3. Interacting with Java
Using Maven dependencies
Clojure interop syntax
Creating an object
Calling an instance method
Calling a static method or function
Accessing inner classes
Writing a simple image namespace
Writing the tests
The let statement
Destructuring in Clojure
Sequential destructuring
Associative destructuring
Exposing your code to Java
Testing from Groovy
Proxy and reify
Summary
4. Collections and Functional Programming
Basics of functional programming
Persistent collections
Types of collections in Clojure
The sequence abstraction
Specific collection types in Clojure
Vectors
Lists
Maps
Sorted maps and hash maps
Common properties
Sets
Sorted sets and hash sets
Common properties
Union, difference, and intersection
Applying functional programming to collections
The imperative programming model
The functional paradigm
Functional programming and immutability
Laziness
Summary
5. Multimethods and Protocols
Polymorphism in Java
Multimethods in Clojure
Keyword hierarchies
isa?
parents
descendants
underive
A la carte dispatch functions
Protocols in Clojure
Records in Clojure
Summary
6. Concurrency
Using your Java knowledge
The Clojure model of state and identity
Promises
Pulsar and lightweight threads
Futures
Software transactional memory and refs
Atoms
Agents
Validators
Watchers
core.async
Why lightweight threads?
Goblocks
Channels
Transducers
Summary
7. Macros in Clojure
Lisp's foundational ideas
Macros as code modification tools
Modifying code in Java
Modifying code in Groovy
The @ToString annotation
The @TupleConstructor annotation
The @Slf4j annotation
Writing your first macro
Debugging your first macro
Quote, syntax quote, and unquoting
Unquote splicing
gensym
Macros in the real world
References
Summary
Index

Clojure for Java Developers

Clojure for Java Developers

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2016

Production reference: 1190216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-150-1

www.packtpub.com

Credits

Author

Eduardo Díaz

Reviewers

Ning Sun

Nate West

Commissioning Editor

Kunal Parikh

Acquisition Editor

Usha Iyer

Content Development Editors

Neeshma Ramakrishnan

Kajal Thapar

Technical Editor

Saurabh Malhotra

Copy Editor

Sneha Singh

Project Coordinator

Shweta H. Birwatkar

Proofreaders

Safis Editing

Indexer

Hemangini Bari

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

Eduardo Díaz is a developer with a strong background in the Java language. He has a passion for functional programming and new programming paradigms. His work includes full stack development, systems design, and high volume real time data processing.

He has worked on every technology related problem you can imagine, as a consultant solving anything related to Java, UNIX, C, or any other strange problem you might have had.

As a developer, he has been working for around 10 years on Java, Python, Scala, Clojure, in the media, bank, and primarily communications industries.

He is currently working at Grupo Expansion, a media company, where he helps design and implement a new content delivery platform aiming to empower content editors and encourage developers to find new ways to use data.

First of all, I would like to thank Neeshma Ramakrishnan and Kajal Thapar at Packt Publishing, they are the best editors, they have an incredible amount of patience and without them, there would be nothing even close to a book.

I would also like to thank my colleagues and friends at Grupo Expansion, Lucasian Labs, and Javanes; they have helped me grow in every way imaginable. Thanks for everything!

Last but not the least, thanks to my family for always keeping up with me, cheering me up, believing in me and helping in everything I do, even when it means not seeing me for weeks or months. I truly value your support!

About the Reviewer

Ning Sun is a software engineer currently working for a China-based startup, LeanCloud, providing one-stop "backend as a service" for mobile apps. Being a startup engineer, he has to solve various kinds of problems and play different kinds of roles; however, he has always been an enthusiast for open source technology. He contributes to several open source projects and has also learned a lot from them.

At LeanCloud, he built a messaging system that supports tens of millions of clients per day. The system is fully powered by Clojure and its ecosystem. He has been an early member of Clojure Chinese community since 2011. He has delivered talks at several meetups and has been very active in the mailing list and open source projects. Ning created Clojure RPC library "Slacker", which is widely used at LeanCloud and several other companies.

He worked on https://Delicious.com in 2013, which is known as one of the most important websites in the early Web 2.0 era.

He has been a reviewer of two books about Solr at Packt Publishing. Also, he was the reviewer of Programming Clojure, Chinese edition.

You can always find him on Github.com/sunng87 and Twitter.com/Sunng.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

In the last few years, we have seen a widespread tendency to create new languages for JVM. There are all sorts of new languages with different paradigms and different ways of working.

Clojure is one of those languages, one that we believe is worth learning.

Over the course of this book, you will learn about Clojure and how opinionated it is. You will learn why immutable objects are not only possible, but it is a good idea to use them.

You will learn about functional programming and see how it fits the concept of immutable programs.

You will understand the very powerful idea of representing your code as a data structure of the same language.

It is important to note that we will build all this knowledge on top of what you already know; this book assumes that you understand the Java language and a bit of how it works. It assumes that you understand how to create classes and objects, how to call methods, and also a bit about the JVM. We will find similarities and differences from the Java language that you already know, so you can understand how the Clojure world works.

It is said that a great programmer is not the one who knows a lot of different programming languages, it is someone who knows different programming paradigms.

Clojure brings ideas from Lisp and functional programming, which are different to what you are used to. This book will help you understand the power behind these ideas and why a language so old still exists and has a place.

Learning Lisp is one of the great pleasures of life, I hope you enjoy it!

What this book covers

Chapter 1, Getting Started with Clojure, is your first step with Clojure, from how to install an interpreter, how to use the IntelliJ plugin Cursive Clojure, and how to start writing your first lines of code in Clojure.

Chapter 2, Namespaces, Packages, and Tests, deals with how every other language needs a way to organize our code. We do it with namespaces, and we start learning by doing little experiments and by comparing with the Java packages we already know.

Chapter 3, Interacting with Java, discusses the fact that one of the most useful features of Clojure is that it can be hosted on top of other platforms. Java is probably one of the most common platforms, and here we learn how to interact with Java code and libraries and how to expose our Clojure code to Java.

Chapter 4, Collections and Functional Programming, tells us that functional programming and immutable data structures (or collections) are fundamental to programming in the Clojure language; here we understand how we can write meaningful programs using immutable data structures and how functional programming is ideal for that.

Chapter 5, Multimethods and Protocols, introduces new tools and ideas of Clojure that help you write much more flexible and simple codes. Destructuring allows you to gain instant access to the data you need from a data structure. Multimethods and protocols are similar to Java's polymorphism but give you a whole new level of flexibility that you could only dream about.

Chapter 6, Concurrency, tells us about how in the modern world concurrency plays an extremely important part. This chapter also tells us about Clojure's native primitives for concurrency and again you will learn why immutable data structures are a great ally when writing concurrent programs.

Chapter 7, Macros in Clojure, deals with the fact that these are not the Excel macros you are used to, they are a way in which you can modify your program's source code at compile time. This is one of Lisp's big ideas and one that gives you immense flexibility. Here we understand a little of how to use this feature.

What you need for this book

You need the Java 8 SDK.

You should be able to run samples on any OS; our samples should be easier to follow in environments where there is a shell available. (We focus mainly on Mac OS X.)

Who this book is for

This book is for developers who are familiar with Java and the JVM.

Ideally, you know how the classloader works, how to generate JAR files and consume them; you are familiar with Java's most common libraries and classes.

If you are not familiar with this, you will be able to follow this book but you won't get the most from the comparisons and samples.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We are using :require to include functions from the clojure.test and the ns-playground.core packages."

A block of code is set as follows:

curl -O https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein# The next step just set up the lein script in your path, you can do it any way you wishmv lein ~/binecho "export PATH=$PATH:~/bin/">> ~/.bashrcsource ~/.bashrc# Everything should be running now, let's test itlein help

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

lein new app getting-started cd getting-started lein run # Hello, world!

Any command-line input or output is written as follows:

lein uberjar

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "After that you can run any tests, just open your test file and go to Tools | Run Tests in the current NS in REPL."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ClojureforJavaDevelopers_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Getting Started with Clojure

Welcome to the world of Clojure! If you are here, you probably know a little about Lisp or Clojure, but you don't really have an idea of how things work in this world.

We will get to know Clojure by comparing each feature to what you already know from Java. You will see that there are lists, maps and sets just like in Java, but they are immutable. To work with these kinds of collections, you need a different approach; a different paradigm.

This is what we will try to accomplish in this book, to give you a different way to approach problems. We hope you end up using Clojure in your every day life, but if you don't, we hope you use a new approach toward problem solving.

In this chapter, we will cover the following topics:

Getting to know ClojureInstalling LeiningenUsing a Read Eval Print Loop (REPL)Installing and using Cursive ClojureClojure's simple syntaxClojure's data types and their relationship to the JVM's data typesSpecial syntax for functions

Getting to know Clojure

Before getting started with Clojure, you should know some of its features and what it shares with Java.

Clojure is a programming language that inherits a lot of characteristics from Lisp. You might think of Lisp as that weird programming language with all the parentheses. You need to keep in mind that Clojure chooses to embrace functional programming. This makes it very different from current mainstream programming languages. You will get to know about immutable data structures and how to write programs without changing variable values.

You will also find that Clojure is a dynamic programming language, which makes it a little easier and faster to write programs than using statically typed languages. There is also the concept of using a REPL, a tool that allows you to connect to a program running environment and change code dynamically. It is a very powerful tool.

At last, you will find out that you can convert Clojure to anything you like. You can create or use a statically typed system and bend the language to become what you like. A good example of this is the core.typed library, which allows you to specify the type information without adding support to the compiler.

Installing Leiningen

We are used to having certain tools to help us build our code, such as Ant, Maven, and Gradle.

In the Clojure ecosystem, the de facto standard for dependency and build management is Leiningen (affectionately named after the short story "Leiningen versus the Ants", which I recommend reading at http://en.wikipedia.org/wiki/Leiningen_Versus_the_Ants); Leiningen strives to be a familiar to Java developers, it gets the best ideas from Maven, like: convention over configuration. It also gets ideas from Ant like custom scripting and plugins.

Installing it is very simple, let's check how to do it on Mac OS X (installing on Linux should be the same) using bash as your default shell.

You should also have Java 7 or 8 already installed and configured in your path.

You can check the detailed instructions on the Leiningen project page http://leiningen.org/. If you want to get a Leiningen installation up and running, this is what you would have to do:

curl -O https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein# The next step just set up the lein script in your path, you can do it any way you wishmv lein ~/binecho "export PATH=$PATH:~/bin/">> ~/.bashrcsource ~/.bashrc# Everything should be running now, let's test itlein help

The first time you run the lein