Book review: Scala Cookbook

Disclaimer: I received this book as part of the O’Reilly Blogger Review program. The opinion about the book below is only my own!

Since O’Reilly published the Perl Cookbook many years ago I have become a huge fan of that style of books. Back then – when I was still using Perl – this book was a tremendous help for all kind of things I wanted to do with Perl. Later the Ruby, Python and Java cookbooks were equally helpful.
Now O’Reilly has pubished a Scala cookbook and I am extremely happy with the result. The book is pretty big with more than 700 pages (and an extra chapter on Play is available from the author’s website because it didn’t make it into the book).

The book covers many things you will encounter daily in your Scala projects from creating classes, using Scala’s amazing collections, reading files to working with actors (using Akka).

Each recipe has a problem, shows and solution and then goes into detail explaining the solution. If you already know other O’Reilly cookbooks, you will be very familiar with the book’s style.

My favorite chapters are the ones on functional programming and the Scala collection library.

The chapters on functional programming are very pragmatic without much theory. You won’t find advanced discussions on Monads (there are other books for this and many websites) but many very useful tips on how to create your own functions and use them (as well as the existing ones from the Scala standard library) effectively in everyday projects.

The two chapters on the Scala collection library are about 130 pages long and explain in great detail the amazing features of what I consider the best collection library for any programming language out there.

The writing is clear and very easy to follow and the sample code is easy to read. Because it is all in small recipes you don’t need to read through lot’s of theory to figure out how to open a file or write a partial function.

Summary:
If you are a beginning or intermediate Scala developer the Scala Cookbook is a must have. Even advanced Scala developers should save time looking up solutions from the book – you just can’t have everything in your head :-)
This book would also make a very good second Scala book to deepen your knowledge after you’ve read an introductionary book (Scala for the Impatient by Cay Horstmann is my favorite)

More information from the publisher:
Scala Cookbook

Book review: MongoDB – The Definitive Guide, 2nd edition

Disclaimer: I got a free copy of this book as part of the O’Reilly Blogger Review program. The opinion here is not influenced by that.
It is only my own and honest opinion of this product.

MongoDB is one of the stars in the NoSQL market (surpassed in popularity maybe only by Cassandra) and several books are now available.
One of the most popular ones has been MongoDB: The Definitive Guide of which a 2nd edition is now available .

The 2nd edition is about twice as big as the first edition and has over 400 pages.

The book covers everything from the basics to replication, sharding, server administration and schema design.
I liked the examples chosen. They are not too complicated and as a reader I could concentrate on the MongoDB stuff and didn’t have to invest a lot of time to understand the business logic of the examples (some books come up with way to complicated examples and then have a hard time explaining what’s really important to the reader).

The text is easy to read and never gets boring. I like the fact that the PDF ebook has syntax highlighting in the code examples, that makes the examples easier to read.

I would have liked to see a short comparison with some other NoSQL databases like Riak or Cassandra but one can find this information online via a Google search easily.

The book is not intended as a guide to all the different drivers for different languages. But when you understand the content of the book, it shouldn’t be too hard to use it from any programming language that has a decent driver for MongoDB like Scala, Java, Python or Ruby.

Summary:
If you are a developer or system administrator working with MongoDB and want a comprehensive, easy to read book, I highly recommend “MongoDB: The Definitive Guide, 2nd Edition”.

More information:

O’Reilly book website:
MongoDB – The Definitive Guide

Video review: Functional Thinking by Neal Ford, O’Reilly Media

Disclaimer: I got a free copy of this video as part of the O’Reilly Blogger Review program. The opinion here is not influenced by that.
It is only my own and honest opinion of this product.

I’ve liked Neal Ford’s freely available talks about functional programming and I’ve attended one of his talks last year at WJAX in Munich. He is a great communicator and has a vast technical knowledge.

Functional Programming is one the rise and in my opinion something every good developer should learn. This new video Functional Thinking is a good way to get started.

In the first part Neal explains why functional programming is something that every developer should now care about. He makes a very good point about why and how functional programming can enrich your toolbox. For example he mentions that Clojure is to concurrency what Java was to garbage collection. While in Java you don’t have to worry much about memory leaks, in Clojure (and of course other functional languages) you don’t have to worry about low level concurrency details like locks.

Neal does a great demonstration showing the beauty of functional code when he transform a verbose Java method from Apache Commons into some beautiful Clojure code and then explains how much better and more general the Clojure version is.

He explains very clearly some of the main concepts of functional programming like laziness, strict evaluation or high-order functions and closures (and it makes you realize how “noisy” Java (before Java 8) is compared to more functional languages like Scala).

Java is used for many examples and when Java doesn’t offer what is needed Neal switches to Groovy most of the time but also shows Scala and Clojure versions. I personally would have preferred more Scala and less Groovy but this is just a personal preference. Functional libraries like Functional Java or totallylazy are also introduced.

I’ve found only one error in the videos: When Option is presented the slide and Neal say that the code is Scala but in fact it is Java.

I really liked Neal’s recommendation to look at the concept of new languages like Clojure instead of just comparing them with Java or C++ or looking at the syntax. Too often programmers ignore the newer languages because the don’t feel familiar at first.

All the code samples are easy to follow and Neal is really great at explaining new concepts to OO programmers who come from a language like Java, Ruby or C++.

Conclusion:
This video is a fantastic introduction to functional programming if you come from an object oriented language and now want to learn more about functional programming or just see what it is all about and why so many people are now talking about it.

Even if you’ve already using functional programming concepts and languages for a while you can probably learn something new or get a new perspective on some functional concepts.
So unless you’ve just written your own Haskell compiler, I highly recommend watching this video to get started with functional programming.

The talk also shows how badly Java needs lambda expressions and a more functional collection library! :-)

After watching that video it is a good idea to download Clojure or Scala and play with it. Neal Ford (together with Stuart Halloway) has recently also released a new almost 6 hour video about Clojure. And Martin Odersky’s free course about Functional Programming Principles in Scala is available online for free (if you don’t want to do the exercises, you can just download the videos).

You can find the video Functional Thinking by Neal Ford here:
Functional Thinking by Neal Ford

Scala: Put a long one line operation on collections in it’s own method

Scala collections are extremely powerful and once you get used to all the methods and different collections you don’t want to get back to other programming languages that don’t offer all that power.
Often you can write rather complex operations in just one line instead of many loops and tempory variables thanks to methods like filter, map, foldLeft, reduceLeft, etc.

But while it is easy to chain such method calls for powerful transformations it can take a while for someone new to Scala to understand your code:
Let’s take the following code as an example. It is a contrived example about how to build a URL query string from a Map[String, String].

val params = Map("fantasy_book_1" -> "The Hobbit",
    "fantasy_book_2" -> "The Lord of the Rings",
    "science_book_1" -> "Tropical Ecology")

val queryString = params.filterKeys(_.startsWith("fantasy"))
      .map(t => URLEncoder.encode(t._1, "UTF-8") -> URLEncoder.encode(t._2, "UTF-8"))
      .foldLeft("?")((a, t) => a + (t._1 + "=" + t._2 + "&"))
      .dropRight(1)

The code is a “one liner” even though it is better to write it in several lines as I did here to make it more readable.
What the code does is build a query string for a URL from keys and values in a Map.
The code is not really difficult.
In the first line uses the filterKeys method to filter out only the books that belong to the fantasy category. The second line does the URL encoding using UTF-8, the builds the query string using foldLeft and at the end calls dropRight to get rid of the last “&”.

This code is quite easy to understand when you have some experience with Scala. You could come up with a similar code in Ruby or even Java 8 using the new lambdas.

But I recommend putting code like this in it’s own method with a good name. This makes it more readable for people new to your code – and to you too when you get back to the code after few months.

The following code shows how this might look like:

  def createFantasyBookQueryString(parameters: Map[String, String]): String = {
    parameters.filterKeys(_.startsWith("fantasy"))
      .map(t => URLEncoder.encode(t._1, "UTF-8") -> URLEncoder.encode(t._2, "UTF-8"))
      .foldLeft("?")((a, t) => a + (t._1 + "=" + t._2 + "&"))
      .dropRight(1)
  }

Calling the method makes the code easier to read and everyone who reads your code does not need to know the details of how you build the query string.

Always try to make the code as easy to read as possible.

Note that I prefer to add the return type to the method declaration. This is not necessary because the Scala compiler can figure it out automatically but it makes the code easier to read and when you change it later and make a mistake and return a different data type the compiler will tell you immediately.

Book review: Confessions of a Public Speaker by Scott Berkun

I like to go to developer conferences. It is great to meat new people and learn something about new technologies like Clojure, Scala or Akka.
Unfortunately sometimes the talks I listen to during conferences are terrible. Very boring speaker, many bullet points, monotone voice and other things make it hard to stay awake after 5 minutes.

Giving good talks is not easy and I have been guilty of giving bad and boring talks myself.

The good news is that public speaking can be learned. Not everybody will be able to speak like Steve Jobs or Barack Obama but everybody can improve. (If you want to learn how Job and Obama do or did it, I recommend The Presentation Secrets of Steve Jobs: How to Be Insanely Great in Front of Any Audience and Say it Like Obama and Win!: The Power of Speaking with Purpose and Vision, Revised and Expanded Third Edition).

The most important thing to do is to actually practice public speaking by giving talks. For next year I plan to give at least one talk a month. All this helps to practice. But practice is only good when you practice how to do it correctly. If you practice bad things you will just get better at doing bad things.

There are many ways to learn how to be a better speaker incl:

  • Listening to talks on youtube
  • Going to great talks and ask the speaker for advice
  • Going to a Toastmasters club near you. (I will do that next year)
  • reading a good book about public speaking

Reading a good book is always a good idea and Confessions of a Public Speaker by Scott Berkun is one of the best books I’ve read so far on public speaking.

It is a much more personal book than most other English and German books I’ve read (or plan to read) on public speaking.

Scott writes about many things a public speaker (from a professional speaker to anyone who wants to give a talk) should know incl:

  • How to deal with your fear of public speaking
  • How to work a tough room
  • How to prepare
  • How to talk on television
  • How not to be boring
  • How realistic it is to make $30,000 an hour
  • How to teach people something
  • Funny and scary stories by other speakers and what went wrong during their speeches

Scott not only explains what went well but also what went wrong during his own speeches.

Scott’s book is not only a great source of information about public speaking, it is a joy to read and often very funny because Scott is also a great writer (check out this blog)

Confessions of a Public Speaker is great for you if you want to give a talk at work or during your free time. No matter what you want to talk about, this book will be helpful. Highly recommend!
Note: Just reading through the book once is a good start but to actually get a lot out of it, it is important to check your talks against the advice in the book and see how you can improve your speeches and presentations!

Get the book from amazon:

Scala Cookbook announced

The cookbooks from O’Reilly are among the most popular books among developers. I was very happy this morning when I discovered that there is now an upcoming Scala Cookbook. I am sure it will be a great book for all Scala developers.
It is written by Alvin Alexander.

Once available, I will publish a review of the book. It is currently schedule for April 2013, according the the publishers website.

Order it from amazon:

New book “Akka in Action” announced

The Akka framework is one of the stars in the Scala and Java world. It was only a matter of time until books would appear.
Now the “Akka in Action” book has been announced. It is scheduled for final publication in Spring 2013 but 2 chapters are already available.
The “in action” serious of Manning has been very good so far and I have several very good books published by Manning about different topics like C++, Java, Scala or Ruby.

More information about the upcoming Akka book can be found here:
Akka in Action

Java concurrency: Understanding CopyOnWriteArrayList and CopyOnWriteArraySet

Java has a huge amount of useful collections and several are made specifically for use in concurrent code like the ConcurrentHashMap.

Two sometimes very useful classes are the CopyOnWriteArrayList and CopyOnWriteArraySet. They implement the java.util.List and the java.util.Set interface respectively.

Let’s focus on the CopyOnWriteArrayList to understand what it is all about. Contrary to the ArrayList, this class is thread safe. This means when you use it from several threads no undefined state can occur in the list.
As will all data structures it is important to understand when to use them. As the name CopyOnWrite says, a copy of the whole list is made each time you write to the list like adding an element or remove an element. As you can figure out yourself, this can be pretty expensive when your list is large.
This means that a CopyOnWriteArrayList (and CopyOnWriteArraySet) is mostly useful when you have few modifications but many reads because reads are very cheap and don’t require synchronization.

When you iterate over a CopyOnWriteArrayList and CopyOnWriteArraySet the iterator uses a snapshot of the underlying list (or set) and does not reflect any changes to the list or set after the snapshot was created. The iterator will never throw a ConcurrentModificationException.

Here is a code example:


import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteTest {

	public static void main(String[] args) throws InterruptedException {

		final CopyOnWriteArrayList<Integer> numbers = new CopyOnWriteArrayList<>(
				Arrays.asList(1, 2, 3, 4, 5));

		// new thread to concurrently modify the list
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// sleep a little so that for loop below can print part of
					// the list
					Thread.sleep(250);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
				numbers.add(10);
				System.out.println("numbers:" + numbers);
			}
		}).start();

		for (int i : numbers) {
			System.out.println(i);
			// sleep a little to let other thread finish adding an element
			// before iteration is complete
			Thread.sleep(100);
		}
	}
}

Note: This is not production ready code, no proper exception handling, etc

Here is the output of this code:

1
2
3
numbers:[1, 2, 3, 4, 5, 10]
4
5

As you can see the for loop only prints the numbers 1-5 and the number 10 is not printed in the for loop as it was not present when the snapshot of the iterator was taken.

Conclusion:
CopyOnWriteArrayList and CopyOnWriteArraySet (which is implemented with a CopyOnWriteArrayList) are special data structures for use cases where you want to share the data structure among several threads and have few writes and many reads.
Always make sure to do a performance test for your code on real hardware to see how it performs in your application. And make sure to read the javadoc for all the methods to really understand how the data structures work.
Of course you can also use CopyOnWriteArrayList and CopyOnWriteArraySet from other JVM languages like Scala, Clojure, JRuby or Groovy.

Immutable collections.
Sometimes you just need to create the list or set once and then later only read from it. In this case I recommend having a look at the immutable collections from Guava.. They are always thread safe (as is every really immutable object) and are a better alternative to the wrapped immutable collections that come with the JDK. See the Guava website for why that is the case.

Book review: The C++ Standard Library – A Tutorial and Reference, 2nd Edition

When Nicolai Josuttis published the first edition of The C++ Standard Library – A Tutorial and Reference, it quickly become one of the most popular C++ books. The fantastic book was a must have for every serious C++ developer who wanted to use the standard library effectively.

Now in 2012, Nicolai Josuttis has published the 2nd edition of this amazing book and although I rarely use C++ anymore and bought a copy to see what has changed since the last edition and how C++11 was different from the older C++ standard.

The book is now over 1,000 pages and additional PDFs are available on the book’s website.

The larger amount of pages was necessary as with C++11 the standard library has grown considerable with many additions like new containers in the STL, libraries for concurrency and much more.

The 2nd edition of the book covers all that is new in the C++11 standard library and also gives an overview of the new languages features like the new for loop, move semantics, lambdas or the new meanning of the auto keyword. I really liked the language overview as all those new things are important now when using the new standard library.

As in the 1st edition everything is explained in great details with many examples and a refence section for all APIs.
The text is easy to read and the examples are very clear and easy to follow.

The book is as complete as it gets. No other C++ book ever covered the standard library in such detail and I doubt that any other book ever will.

I really like the 2nd edition of the book and it is as great as the 1st edition and fully up to date with the latest C++11 information.

For C++ programmers, buying this book is a no-brainer.
Even for Java, C#, Scala or Python programmers I think this is a great read – learning another language is always a great way to improve your programming skills. Even people who don’t like C++ and prefer to use other languages like Java C# (and there are often very good reasons to do so and I also use JVM based languages most of the time) they will often admit that the C++ standard library is one of the best written software libraries out there. This book will help you understand why.

The C++ Standard Library – A Tutorial and Reference, 2nd Edition is a MUST READ for everyone using or learning C++ and it will be your constant companion when writing C++ code.

You can order it from amazon here:

amazon.com amazon.co.uk amazon.de

Clojure gets Reducers – A Library and Model for Collection Processing

I just read this announcement about Reducers – a library and model for collection processing.

What I really like are the capabilities to process collections in parallel using Java’s Fork/Join Framework with the new fold function.

This is a great addition to Clojure – and a great time to add Clojure to your programming toolkit.

I just got my copy of the new Clojure Book by Chas Emerick, Christophe Grand, Brian Carper. The first 100 pages are awesome and I am sure so is the rest of the book. This book is a great way to get started with Clojure.

By the way: If you like parallelism and collections, make sure to also have a look at Scala’s Parallel Collections.