Scala: Implementing Factory

In a previous post we explained the Design Pattern Factory Method and how it differs from the Builder Pattern. Now we will explain how to implement this pattern in Scala. However, first we need to learn a new concept in Scala: the Companion Objects.

Companion Object

Previously, we said that a Companion Object could be seen, from a Java point of view, as a Static Class.

A Companion Object is an Object that shares the same name and source file with another Class or Trait. A Trait could be seen as a Java Interface.

The Companion Object is useful for implementing utility methods, factories, apply and unapply methods…

When it does exist a Companion, the class is called Companion Class and the object is called Companion Object. This name’s collision is possible because they don’t share the same namespace. While classes are stored in the type namespace, objects are stored in the term namespace. You can read the Scala language specifications here.

Implementing Queue Factory in Java

We want to implement a factory that produces different types of shapes depending on the number of sides given.
First of all, we need the abstract class. In this example it could be an interface, but we could also add some other common properties as fill colour, line colour…

package com.wordpress.j2eethoughts.factory; public abstract class Shape { public abstract double getArea(); public abstract double getPerimeter(); }

We will work with two different kinds of shapes: triangle and rectangle. Here comes the code for Triangle:

package com.wordpress.j2eethoughts.factory; public class Triangle extends Shape { private double ab; private double bc; private double ac; public Triangle(double ab, double bc, double ac) { super(); this.ab = ab; this.bc = bc; this.ac = ac; } @Override /** * Heron's way */ public double getArea() { double s = getPerimeter()/2; return Math.sqrt(s*(s-ac)*(s-ab)*(s-bc)); } @Override public double getPerimeter() { return ab+bc+ac; } }

And this is the source for Rectangle:

package com.wordpress.j2eethoughts.factory; public class Rectangle extends Shape { private double height; private double length; public Rectangle(double height, double length){ super(); this.height = height; this.length = length; } @Override public double getArea() { return height*length; } @Override public double getPerimeter() { return (height*2)+(length*2); } }

And finally, the source of the factory:

package com.wordpress.j2eethoughts.factory; public class ShapeFactory { public static Shape getShape(double len1, double len2, double len3){ return new Triangle(len1,len2,len3); } public static Shape getShape(double len1, double len2){ return new Rectangle(len1,len2); } }

After this, we can test this classes with this little application:

package com.wordpress.j2eethoughts.factory; public class Main { public static void main(String[] args) { Shape sh1 = ShapeFactory.getShape(32.34, 23); System.out.println(sh1.getArea()); System.out.println(sh1.getPerimeter()); Shape sh2 = ShapeFactory.getShape(5, 3, 4); System.out.println(sh2.getArea()); System.out.println(sh2.getPerimeter()); } }

Implementing Queue Factory in Scala

If we want to implement this shape factory in Scala we will need only one source file. We will use a companion class Shape and a companion object Shape, this last one will act as a factory. Therefore, the concrete implementations of Shape will be private classes of the companion object. With this approach, we hide any concrete implementation of Shape from the client.

This is the source code for the companion class and object.

package com.wordpress.j2eethoughts.queue import scala.Math.sqrt abstract class Shape { def perimeter : Double def area : Double } object Shape { private class Triangle (ab : Double, bc : Double, ac : Double) extends Shape{ override val perimeter = ab + bc + ac private val s = perimeter / 2 override val area = sqrt(s*(s-ac)*(s-ab)*(s-bc)) } private class Rectangle (height : Double, length : Double) extends Shape{ override val perimeter = height * 2 + length * 2 override val area = height * length } def apply(ab : Double, bc : Double, ac : Double) : Shape = new Triangle(ab,bc,ac) def apply(height : Double, length : Double) : Shape = new Rectangle(height,length) }

I would like to make some considerations about this implementation. When we override a method, the keyword override is mandatory, it won’t compile if it’s not included. Furthermore, it’s possible to override a method with a variable. If you look at the concrete classes, the abstract methods defined in Shape are overridden with a val.

Now we will test the Shape Factory:

package com.wordpress.j2eethoughts.queue object Main { def main(args : Array[String]) : Unit = { val sh1 = Shape (32.34, 23) println(sh1.area) println(sh1.perimeter) val sh2 = Shape (3,4,5) println(sh2.area) println(sh2.perimeter) } }
Advertisements

Scala: Overloading Operators

If you come from Java I have just caught your attention. If you are a C++ developer you might be not surprised.

In Scala, every operator is actually a method. The difference between methods and operators is how you use them. When you write:

val = 3 + 5

Scala calls the method + defined in Int:

val = (3).+(5)

In the first example + is used as operator, in the second one, + is used as a method.
As said, every operator is a method, which means that we can call any method as an operator. For instance, this two instructions are equivalent:

val test1 = “Alice” startsWith “A”
val test2 = “Alice”.startsWith(“A”)

After reading this, you might be wondering: Scala doesn’t really have operator overloading, it is only method overloading. Well, maybe it’s true, but from the language point of view, it is operator overloading!

There are three types of operators, infix, prefix and postfix. In Scala you can implement these three kinds, but there are some restrictions about the prefix and postfix operators.

Infix

In infix notation, you put the operator between the objects. This kind of operators could take two or more operators. When having more than two, all but the first go after operator between parenthesis.
Now let’s do a real example where it could be useful this infix operator overloading.

class Angle (d: Int, m: Int, s: Int) { require (d < 360 && m <60 && s < 60) val degree: Int = d val minute: Int = m val second: Int = s def + (that: Angle) : Angle = { val sec = second + that.second val min = minute + that.minute + (sec /60) val deg = degree + that.degree + (min /60) new Angle (deg % 360,min % 60,sec % 60) } def + (deg: Int) : Angle = new Angle (degree + deg % 360, minute, second) def - (that: Angle) : Angle = { val thisSecs = degree * 3600 + minute * 60 + second val thatSecs = that.degree * 3600 + that.minute * 60 + that.second val dif = if(thisSecs <= thatSecs) thisSecs - thatSecs else thatSecs - thisSecs val min = dif / 60 val deg = min /60 new Angle (deg , min % 60, dif % 60) } override def toString = degree+ "º "+minute+"' "+second+"''" }

After creating this class, we can add and subtract angles as follows:

val angle1 = new Angle(40,30,35)
val angle2 = new Angle(30,52,50)
val angle3 = angle1 + angle2
println(angle3)
println(angle1 – angle2)
println(angle2 – angle1)
println(angle3 – angle1)

And the result is:

71º 23′ 25”
9º 37′ 45”
9º 37′ 45”
30º 52′ 50”

This example above is only a proof of concept of operator overloading. Maybe it’s not programmed in a functional way, but I’ve done my best. Any comments are appreciated.

Prefix

In prefix notation, you put the operator before the object. In Scala, the prefix operators can only take one operator, this is called unary operator. The only identifiers that can be used in unary prefix operators are +, , ! and ~. If you need to define a prefix operator, for instance, !, you must implement a method called unary_!.

Postfix

In postfix notation, you put the operator after the object. This kind of operators are also unary. Unlike the prefix operators, in postfix operators there is no restriction about the names of the methods/operators. The convention about postfix operators is invoking the operators without parenthesis only if the operator has no side effects, otherwise, you might include them. For example, method toLowerCase defined in String should be invoked without parenthesis and println() should be invoked with parenthesis because it writes to the Console.

XStream

XStream is a library to serialize objects to XML and vice versa. It must not be used as a XML processor.

The way that XStream serializes and de-serializes objects is by using Annotations. This post will show you how to annotate a class and how to serialize it.

First of all let’s introduce the class:

public class Book { private String isbn; private List author; private String title; private int pages; //class continues... }

This class models a book. It has the ISBN, a list of authors (it’s only a String per author), the title and the number of pages. The point of XStream is that it uses reflection to serialize and de-serialize the objects.
We want to serialize this book to this XML:

<BOOK> <ISBN>978-0-9815316-0-1</ISBN> <AUTHOR>Martin Odersky</AUTHOR> <AUTHOR>Lex Spoon</AUTHOR> <AUTHOR>Bill Venners</AUTHOR> <TITLE>Programming in Scala</TITLE> <PAGES>736</PAGES> </BOOK>

The next step is to annotate the class:

package com.wordpress.j2eethoughts; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.util.List; @XStreamAlias("BOOK") public class Book { @XStreamAlias("ISBN") private String isbn; //no annotations private List author; @XStreamAlias("TITLE") private String title; @XStreamAlias("PAGES") private int pages; //class continues... }

Note that lists must not be annotated. After this, we need to create the facade of XStream:

package com.wordpress.j2eethoughts; import java.util.ArrayList; import java.util.List; import com.thoughtworks.xstream.XStream; public class Main { public static void main(String[] args) { XStream xs = new XStream(); xs.processAnnotations(Book.class); xs.addImplicitCollection(Book.class, "authors", "AUTHOR", String.class); List authors = new ArrayList(); authors.add("Martin Odersky"); authors.add("Lex Spoon"); authors.add("Bill Venners"); Book book = new Book("978-0-9815316-0-1", authors,"Programming in Scala", 736); System.out.println(xs.toXML(book)); } }

And that’s all, now you can serialize any Book object. For de-serialization you must call the method xs.fromXML passing a String to the method.

Scala: Arrays, Lists, Sets and Maps

Despite all Scala code is translated to Java code, there are some differences between Scala Collections and Java Collections. In this post we will try to explain four types of collections: Arrays, Lists, Sets and Maps.

Arrays

In Scala, in contrast to Java, there is an Array object and it can be created in the same way as Java does. However, the syntax differs. The first one is the classical way to create an object.

var classicWay = new Array[String](3)
classicWay(0) = “The”
classicWay(1) = “classic”
classicWay(2) = “way”

There are two important differences to notice. The way to specify the type of the Array is [] instead of <>. The other one is the way to instance the array, in Scala we use the () instead of []. There is also another way to create and initialize an Array, which is less verbose and more compact.

var compactWay = Array(“I”,”like”,”this”,”way”)

As it can be seen, there is no need to specify the type of the Array, the compiler will infer that the type is String. Here there is another difference, we use the companion class to get an instance of Array. Companion classes will be explained in another post, but they can be seen as static classes or utility classes.
Obviously, we can’t access a position of the Array with the [] operator, instead, the () operator is used. For instance:

print(compactWay(1))
compactWay(0) = “We”

It will be transformed into:

print(compactWay.apply(1))
compactWay.update(0,”We”)

Lists

Lists in Scala are always immutable (in Java they can be mutable), they are designed to enable a functional style programming. That means that, once created, a Scala List can’t be modified. But there are operators on Lists, so maybe you would be wondering why there are operators on Lists if they are immutable objects. As in Strings, when you invoke any operation on a List, another List is created and returned when an operator is applied. Maybe, the two main operators are ::: and :: . The first one is the operator for list concatenation. The second one is the operator to prepend an element to a List. Yes, you read it well: prepend (in Scala you can’t append elements to a list). This is because prepend an element at the beginning of a list is a constant-time operation, whereas append is a linear-time operation. Usually, the owner of an operation is the left operand, but in :: the owner is the right operand. Here there are some examples.

val list1 = List(“This”,”is”)
val list2 = List(“a”,”list”)
val list3 = list1 ::: list2
val list4 = “Hey!” :: list3
println(list1)
println(list2)
println(list3)
println(list4)

List1 and list2 remain immutable, they didn’t change. List3 is a new list resulting of concatenating list1 and list2. In list4, the String “Hey!” is prepended to list3. The complete api of List object can be found here.

Sets

There are two kinds of Sets, the immutable and the mutable one. The difference between mutable and immutable objects is that when an object is immutable, the object itself can’t be changed. The most known immutable object in Java is String: once you have created a String, it remains the same until it is destroyed.

By default, Scala uses the immutable Set. If you want to use the mutable Set, you’ll have to import the class. The hierarchy of the Set is the following:

Hierarchy for the Scala Set object

It’s not a problem to change between mutable and immutable collections, since all of them share the same contract. In most cases, no change will be necessary.

You can create a Set in the same way you create a List. The most useful operations are + and +=, but the second one it’s only available in mutable Sets. In the immutable Sets  mySet += “foo”  is transformed to mySet = mySet.+(“foo”). Here there is a simple example of immutable sets:

var trilogies = Set(“The Godfather”, “Lord of the Rings”)
trilogies += “Millennium”
println(trilogies)

In this example, a new Set is created in line 2. If we import the mutable Set, in this same line, the trilogies set will be modified:

import scala.collection.mutable.Set
var trilogies = Set(“The Godfather”, “Lord of the Rings”)
trilogies += “Millennium”
println(trilogies)

Maps

As in Sets, there are two kinds of Maps, the immutable and the mutable ones. The hierarchy of Map is analog to Map’s hierarchy:
Hierarchy of Scala Set
There are two ways to create a Map in Scala, one of them can only be used with the mutable Maps:

import scala.collection.mutable.Map
var steps = Map[Int, String]()
steps += (1 -> “Go straight on”)
steps += (2 -> “Take the second turn on the left”)
steps += (3 -> “It’s opposite the hairdresser”)
println(steps(3))

Obviously, this Map needs to be mutable, because it has been modified since its creation. Ok, we know how to create mutable Maps, but how immutable Maps can be created?

var steps = Map (1 -> “Go straight on”, 2 -> “Take the second turn on the left”, 3 -> “It’s opposite the hairdresser”)
print(steps(3))

Here again, there is no need to specify the type of the Array, the compiler will infer that the type is Int for the keys and String for the values. The operator -> is useful for creating Tuples. A Tuple can be seen as an array of objects, but they don’t need to share the same type.

Scala: Hello World!

Nowadays, there are many languages running on the Java Virtual Machine, but in the beginning, the JVM could run only compiled Java programs, now we have plenty full of new languages, some of them designed expressly for the JVM, others that had a version capable of running on it.

People is wondering which will be the Next Big JVM Language. There are many candidates who fight for being the chosen one. Scala, JRuby, Jython, Groovy, Clojure are among them.

Recently, a great book came to my hands, Programming in Scala. A comprehensive step-by-step guide, it’s co-authored by Martin Odersky, Lex Spoon and Bill Venners. Mr. Odersky is the creator of the Scala language and also the co-designer of Java generics. In this post, a Hello World example in Scala will be made.

The very first thing to do is download the Scala distribution, you can find it here. The last stable release is 2.8.0. Now the Scala interpreter is installed in our system. With this interpreter, our first Scala program can be done and executed.

Scala is an Object Oriented and a functional programming language. It can be executed within a Java code and vice versa. The semicolon at the end of each instruction is optional, so you don’t have to put it at the end of every sentence. It is less verbose than Java, thus some type declarations can be omitted. For instance, you can say:

var x = new HashMap[int, String]()

Instead of:

var x Map[int, String]() = new HashMap[int, String]()

These are only a few characteristics of Scala. Now,let’s continue with some glossary:

  • val: It’s a variable that could not be modified, it’s like a final variable in Java. Once assigned, it can’t be reassigned
  • var: It’s a variable, it can be modified
  • def: It defines a function
  • print and println: prints the passed the String to the standard output. It’s similar to System.out.println in Java
  • while: the instruction for loops
  • if: the instruction for deciding
  • (paramName1 : Type, paramName2 : Type => paramName1 + paramName2): also is the format of literal functions.
  • foreach (element => action) : the instruction for iterations
  • for (element <- elements): another instruction for iterations, element is a val not a var

Let’s put it all together. The first example is a simple Hello World!. Put the following code into a file named hello.scala

println(“Hello World!”)

Then from the OS prompt, execute:

$> scala hello.scala

The result will be:

Hello World!

Let’s make a more sophisticated sample. Definition of factorial function and execution with the first number typed in the standard input.

def factorial ( x : Int ) : Int = { if ( x == 0 ) 1 else x * factorial ( x - 1 ) } println(factorial(args(0).toInt))

And yet, another example. Capitalize the words typed in the standard input.

args.foreach(arg => print(arg.capitalize))

Executing this:

$> scala capitalize.scala hello world !

The output will be:

HelloWorld!

Introduction to: Patterns of Design (III)

If you search this words on google, factory vs builder pattern, you will find thousands of web pages which try to explain the difference between this two patterns.

We could say that the main difference between them, is the type of complexity in creating the product. So, when the product must be created step-by-step, you’d rather use the Builder Pattern. Otherwise, when the product is created in a single action, the Factory Method must be chosen. In this post, we will focus on this last pattern.

Class Diagram for the Factory Method Pattern

The purpose of Factory Method Pattern is to decouple the concrete products from the client, which will be only coupled with an interface of Product. As it can be seen, this pattern is useful when there is a hierarchy of Product.

Actually, a client must only know about the Product interface and the Creator abstract class. He is isolated from the concrete implementations of both Creator and Product.

Now we will see a situation where this pattern could be applied. We need to model a Soda Factory. This factory (Creator abstract class) produces different kinds of soda (soda is the interface, and each kind of it is a concrete class). The Creator is not supposed to know about any kind of soda. Each concrete class, extending Creator, will override the FactoryMethod and will produce an implementation of Product interface. The clients of this model, will know that there is a Creator and a Product interface, but they don’t care about the concrete classes. When using Factory Method pattern, from the client’s point of view, the Product is created as a result of invoking only one method. On the other hand, when the Builder Pattern is used, the creation is made step-by-step.

This table summary may help.

Builder Pattern Factory Method Pattern
There is no hierarchy of Products (or it’s very simple) There is a hierarchy of Products
Products are created step-by-step Products are created only in one step
Subclasses of Builder know about steps of creation Subclasses of Creator will create a concrete type of Product
The creation steps are very clear The creation algorithm may differ from one type of Product to another

Introduction to: Patterns of Design (II)

In this next chapter another type of pattern of design will be introduced, the creational one. There are some differences between this kind of patterns and the behavioral types (a type of last one was described in part one), the most important thing is, while behavioral centers itself on the algorithms and how the object works, the creational pays attention in how the object is created.

We will decide to apply this kind of patterns when we need to focus in the creation of the object, and this creation is a highly complicated process. The concrete pattern shown in this introduction is the Builder Pattern.

The Builder Pattern is recommended when the algorithm for the creation of the object it’s very clear and it composed by very well-defined steps. The complexity of the creation lies on the different algorithms that might be used in the steps. Maybe a little class diagram should help:

Builder Pattern Class DiagramAs we can see in the class diagram, the Director is the only class that knows about the whole creation process. The Director it’s only coupled with the abstract Builder, so it has no dependency on the concrete classes. A concrete Builder class instance must be passed to the Director.

The Director knows which methods of the Builder class must be called, and in which order, what doesn’t know it’s what each method does, of course. Each concrete Builder class model a specific algorithm for the Product creation. In order to ensure that, the concrete classes must override the methods defined in the abstract class, except those ones that are generic enough.

Let’s apply this pattern in a real example, well maybe it isn’t very real, but it will be useful. Imagine that we need to model the Automated Letter Maker. Given a set of concepts (sender, subject, name…) the application must create different kinds of letters (friendly, formal, business letter…). All the letters has the same parts: header, greeting, body, complimentary clause, signature and postscript. Lets put it all together in another class diagram.

Class Diagram for Automatized Letter MakerThe Writer class knows the algorithm for writing a letter, first is the header, then de greeting… and ends with a possible postscript. But this class doesn’t know how to write it in the proper style (formal, business…). Each concrete builder knows how to write each part in the appropriate type. Finally the Letter is the output of any kind of builder.

Why this pattern is suitable for this example?

  • The output it’s always the same: a Letter.
  • The steps of the creation of a Letter are very clear.
  • There are different ways to implement each step.
  • The addition of new types of builders has the less possible impact in the model.

*All diagrams are made with StarUML.