Factory Method Pattern in Scala

Continuing on with my series of design patterns in Scala, here’s an example of the Factory Method pattern. Since this pattern is as OO as you can get, there’s not as major of a difference in approach from languages like Java as there was with some of the other patterns. But as you hopefully have learned to expect, Scala has a few innovations that make the pattern more elegant! These include sealed traits, apply methods, and pattern matching.

Continue reading “Factory Method Pattern in Scala”


How Scala Even Does One Better Than The Adapter Pattern

UML Diagram of The Adapter Design Pattern
UML Diagram of The Adapter Design Pattern

The Adapter Pattern is a way to allow one object to be used as another object, usually by creating a wrapper class around the first object which implements the same method or methods. There are various versions. I suppose the correct OO way is to implement the same interface as the other object.

Scala has a powerful language feature called implicit classes that improves the pattern.

Continue reading “How Scala Even Does One Better Than The Adapter Pattern”


How Scala Embarrasses the Decorator Pattern

The Decorator Pattern is one of the most popular design patterns. It is used in places where everyday programmers probably don’t think much about it, like the way streams in Java can wrap each other adding or modifying functionality as needed.

Scala traits are often thought of as just a kind of hybrid of Java interfaces and abstract classes. But actually Scala’s traits and specifically their “stackability” totally kills the decorator pattern. I’ve covered stackable traits before on the blog. Bill Venners covers stackable traits in more detail.

Once you play around with stackable traits, I don’t think you’ll ever think of doing something like the above UML diagram in Scala code. Nevertheless, it’s the only option in other OO languages. In short, good bye decorator pattern. Scala has you beat.

Use Java’s world-class sorting algorithms on your custom objects

A lot of people don’t realize that the standard Java libraries are kept up-to-date with world-class sorting algorithms. For example, Java 7 released with an implementation of Timsort for Arrays.sort.

Class/Method Type of Collection Algorithm
Arrays.sort array timsort (objects) or dual-pivot quicksort (certain primitives)
Arrays.parallelSort array merge sort
Collections.sort List merge sort

If you’re not familiar with the Comparable or Comparator interfaces, now might be the time. As long as your object implements Comparable you can use the above sort methods from the standard library. There are often great uses for Comparator as well, especially when you want multiple ways to sort the same objects. For the rest of the post I’ll deal just with Comparable.

Continue reading “Use Java’s world-class sorting algorithms on your custom objects”