Sunday, April 26, 2009

Some more impressions of Python

List comprehensions: List comprehensions are pretty neat. Before studying Python I did not know what they were. This is a wonderful way to perform some operation on an entire list. Let me explain with an example. Let's say we have a list of numbers and want another list containing the double of all the numbers greater than 5 from the first list. In Java we would have to do something like this:

private static List getDoubleOfMembers(List numbers) {
List result = new ArrayList();
for(int num : numbers) {
if(num > 5) {
result.add(num*2);
}
}
return result;
}

However, in Python we can perform this operation using list comprehension like this:

[n*2 for n in numbers n > 5]

Isn't this nice?

Lambda expressions: Python supports Lambda expressions but it does not support closures like Groovy. I wish Python supported closures.

Unchecked exceptions: The blogosphere has had more than it's share of discussions on checked vs. unchecked exceptions. I will not spam your feed reader with any more on this topic. Suffice to say, I like them. In case you want to read more about this debate, this Developer works article is a good starting point.

Pickle: Python has a module called pickle for object serialization and deserialization. Using pickle we can save an object to a file and then reconstruct it as well. We can also use pickle to transmit objects over Internet sockets. There is C implementation of pickle called cPickle which is many times faster. Python does not seem to use anything to signify that an object can be pickled (like the Serializable interface of Java), however, it does have a notion of picklable and non picklable objects. I am still not sure if Python has the equivalent of SerialVerUID for forward compatibility of serialized objects.

repr: Python has a function called repr() which converts an object into a canonical (stringified... if that is a word :-) ) form.
Call repr(obj) to get the string form of an obejct. The return value can be controlled by implementing the __repr__() function in the class. Typically the following should be true:

eval(repr(obj)) == obj

I like this statement. Joshua Bloch wrote in his book Effective Java, Item 9, that if a class's toString() method is documented, then it should return a string such that we should be able to recreate a similar object from that string using the class's String constructer. The repr() function fulfills that criteria.

Saturday, April 25, 2009

My first impressions of Python for the second time

I had worked a bit in Python many years back. Since then I have forgotten almost everything I learned back then. I think the phrase "Out of sight out of mind" applies perfectly to my mind.

Since the last few days, I have started relearning Python, and this time I am recording my impressions of Python after having come to it from a Java background.

Indentation: Python uses indentation to specify blocks of code, instead of curly braces. I like this, because we anyways indent code to increase readability, so why not achieve two tasks together. Code looks much cleaner without the curly braces. However there may be a little downside. Everyone in the team will have to set up their IDE's in the same way. Things might fall apart if some people use tabs and others use spaces for indentation.

Access modifiers: Python does not have public, private, and protected keywords. Everything is public. However, private members can be specified with a leading single underscore. If we use double leading underscores then Python's runtime will do name mangling and make it difficult to directly access those members. Note that I use the word difficult, and not impossible. Personally I like not having access modifiers. Using convention to specify a member as private is fine in my books, because I have never thought of access modifiers as a security feature. It is rather a feature that prevents well meaning programmers from making mistakes. If there is a simple convention like leading underscores signifying a private member, then well meaning programmers will not access it directly. We do not need to treat developers as children and put fences all around the place.

String interpolation: In a previous blog post I wrote about how Python supports string templating, but not interpolation. This is one feature I wish Python supported.

String and Unicode: Python strings are not Unicode by default. For Unicode strings there is a separate Unicode type. On the other hand in Java all strings are always Unicode. Update: Some friends just informed me that Python 3000 has Unicode strings by default.

Multiple inheritance: Python supports multiple inheritance. Again I am not sure I like this.

Numbers: I tried this code in Python

max64BitInt = 2**64 - 1
bigNum = max64BitInt + 126
print 'This is a big number ', bigNum

and it prints the answer correctly. So Python does not have the 64 bit limit for integers the way Java does. In Groovy, numbers can be BigInteger types and can be arbitrarily large. I do not know if this is true in Python. However what we have is definitely better than Java's support for working with large numbers.

Magic method: Python has magic methods. These methods begin and end with double underscores, like __str__(). Magic methods in Python have special meaning, in that they exist to be called back when a certain procedure is invoked. For instance the __len__() method of object o is invoked when we call the len(o) function. It returns the logical length of the object. This is a nice feature because it allows the system to have certain standard functions like len(), repr(), print(), etc and allow developers to have magic methods in their classes if they want their classes to respond to these standard functions. This is how Python also supports operator overloading, as well as list iteration and indexing.

Procedural and OO programming styles: Even though everything in Python is an object, Python supports both procedural and object oriented programming styles. I believe it is also possible to write functional code in Python. But I do not know enough about it. That is a topic for a future post. I like support for procedural programming, because it makes it easy to create small useful scripts. One of the reasons I could never write those in Java was because I would have to create a class and a main method and also put the script through the compile phase. But then again, Java was never meant to be a scripting language. Python also has globally available functions like len(), print(), repr() etc. For example len(o) takes an object o, (maybe a list or a string), and returns it's length. In Java we would have invoked o.length(). I guess there are pros and cons to both approaches. Java's style is more object oriented, but it does not guarantee uniformity. We use the length attribute to get an array's length and the size() method to get the length of a List. In Python if an object o has a logical length, we can get it by invoking len(o).

I have some more impressions on Python, which I will publish in the next post.

Wednesday, April 22, 2009

String interpolations in different languages

I am learning Groovy and refreshing my Python skills as well. While working on some examples, I realized that the operation of concatenating string to produce a larger string is a very frequently used operation. Very often parts of the string we are creating are already held in variables. A crude way of creating the larger string, is to simply concatenate everything as shown in this simple toString() method of the Person object.


public class Person {
//showing only relevant code
public String toString() {
return "Name: " + name + " salary: " + salary + " address: " + address;
}
}


However, this is not very readable. A better way is to use either string interpolation or templating. Java gives us a couple of ways to do templating.

We can either write the toString() method like this to become much more readable:


public String toString() {
return String.format("name: %s salary: %d address: %s", name, salary, address);
}


Or we can use the MessageFormat class:

return MessageFormat.format("name: {0} salary: {1} address: {2}", name, salary, address);


I personally think the last option is more readable. Moving to Python, it also gives us ways to do templating:


return "name: %s salary: %d address: %s" % (name, salary, address));


There is yet another way:

print "name: %(name)s salary: %(salary)d address: %(address)s" % locals()


Notice that both, Java and Python, support templating but not interpolation. Groovy on the other hand supports interpolation which is far more elegant and concise.


public class Person {
//showing only relevant parts of the code
public String toString() {
return """name: ${name} salary: ${salary} address: ${address}"""
}
}

Sunday, April 19, 2009

Create mock objects with metaprogramming

We usually create mock objects in our test suites for those classes which communicate with some external entity that we cannot (or do not care to) setup in our test cases. However, mocking is possible only when we have used dependency injection properly. If we have classes that instantiate their own dependencies then we cannot mock the dependencies. Sometimes our mock solutions may also be time intensive at runtime. I will explain this later in the post.

One solution (the correct one) is to refactor the code and use proper dependency injection to allow classes be be mocked. However, when we have a huge code base of non DI code, which cannot all be changed at a time, then we just have to make so with fewer unit tests. But all is not lost. If we use a dynamic language like Groovy to write the test cases then we can use metaprogramming to change a classes methods at runtime instead of creating mock classes.

I am building a command line Twitter client in Groovy. I have a class called FriendsTimelinePlugin.groovy which periodically fetches content from the friends timeline service in Twitter. There is a class called Net which encapsulates code to make GET and POST reqests. The FriendsTimelimePlugin.groovy class uses Net.GET(url) to invoke Twitter's API to get the XML feed. I obviously did not want to connect to Twitter for the unit test.

I had two options. The first one was to start an instance of Jetty in the in memory mode and get FriendsTimelinePlugin to use a local URL which would talk to my local instance of Jetty instead of Twitter. I could then create handlers in Jetty to mock the reply. This is a good solution, but it would involve additional classes to create the mock handlers for Jetty and it is also time expensive to setup Jetty at runtime. If we have several such unit tests, then it would take enormous time to start and stop Jetty for each unit test.

Below I show an example of how I mocked Net.groovy and FriendsTimelinePlugin.groovy using metaprogramming while creating unit tests.



public void setUp() {
//mock Net.GET(...)
Net.metaClass.static.GET = { url ->
def xml
if(url.contains('since')) {
xml = """<statuses>
<status>
//not showing the entire string containing status code
</status>
</statuses>"""
return xml
}
else {
xml = """<statuses>
<status>
//not showing the entire status string
</status>
</statuses>"""
return xml
}
}

//change the output PrintWriter in FriendsTimelinePlugin
def mockedOut = new PrintWriter(new StringBufferWriter(_buff))
FriendsTimelinePlugin.metaClass._out = mockedOut
FriendsTimelinePlugin.metaClass.filter = ['user_one', 'user_two']
FriendsTimelinePlugin.metaClass.interval = 500
}



In Groovy we can change the implementation of a method using the class' ExpandoMetaClass. This is done by associating a closure with the method to change. In my code, FriendsTimelinePlugin.groovy invokes the Net.GET(url) method to make a GET request to Twitter. I redefined the GET method at runtime so that it does not do any network communication. Instead it will simply return an xml which otherwise would have been returned after fetching it from Twitter. If you look at the code above you will see a line similar to this



Net.metaClass.static.GET = { url ->
//mock implementation
//directly return XML
}



This code replaces the actual implementation of the GET method in Net.groovy with the implementation provided in the closure. The metaClass' static property is used because Get is a static method. As you can see the mock implementation returns an XML string directly instead of fetching it from Twitter.

If you look towards the end of the setup method I am also changing _out in FriendsTimelimePlugin. This is the output stream to which it prints the latest twits. In my test case I have redirected it from System.out to an output stream which writes to a StringBuffer whose contents can be verified in the test case.

I realize that if this mechanism of using metaprogramming instead of creating mock objects is used injudiciously then it could lead to really bad code. Especially dangerous is mocking select methods of a class without understanding how and where it is used in the entire codebase. This can lead to undesired side effects and a totally unmanageable test suite. However, if used carefully this mechanism can not only make it possible to write test cases for classes, which were earlier not possible, it can also reduce the time for running a test suite because we will not have to incur the cost of starting/stopping test servers.

Friday, April 17, 2009

Eclipse's JUnit test runner forcibly terminates threads

Today I was writing a unit test which instantiated a class, which started a thread to do some stuff. I was hoping to test the side effect of that thread. However, to my surprise, I realized that Eclipse would forcibly terminate the test after the test method exited, even before the thread completed it's work.

I wrote a simple test to show this.


import com.sun.org.apache.xpath.internal.operations.And;
import junit.framework.TestCase;
import junit.textui.TestRunner;

/**
* This class shows that Eclipse's JUnit test case runner will forcibly terminate
* the JVM and all running threads
*/
public class ThreadTest extends TestCase {

static Runnable run = new Runnable() {
public void run() {
int cnt = 0;
while(true) System.out.println(cnt++);
}
};

public void testThread() {
Thread t = new Thread(run);
t.start();
}

public static void main(String args[]) {
TestRunner runner = new TestRunner();
runner.run(ThreadTest.class);
}
}


This class basically starts a Thread which prints an increasing count in an infinite while loop. When I run this class as a unit test from Eclipse, the count is printed till about 1890 and then the thread terminates. However, when I run the main method (which runs the unit test using JUnit's TestRunner) then the test runs as expected.

I actually added the main method to eliminate the doubt that JUnit might be terminating the thread. I know this is unlikely, but I just wanted to be sure.

I just find it strange that this is the first time I have run into this issue. Especially after working for so many years with Eclipse. I find it hard to believe that I have never written a test case which started a thread and had to wait for it to do something. Or maybe this is a bug in the latest version of Eclipse (3.4.2).

For now I have worked around this issue by putting the main thread to sleep till a property indicating that that the thread has completed it's work is set.

Wednesday, April 15, 2009

Injecting methods in Groovy with ExpandoMetaClass

I am writing a Twitter client in Groovy. One of the things I want to do is create a thread which will poll Twitter for new updates at regular intervals, and go to sleep when it is not doing anything.

The way we write such code is to invoke the sleep method with the number of milliseconds to sleep. To sleep for 2 minutes, I would write:

Thread.sleep(1000 * 60 * 2)

This code is fine, but not very readable. I would have preferred to write something like this:

Thread.sleep(2.minutes())

This is not possible in Java, but it is in Groovy. In Groovy we can inject methods into a class at runtime. This is done using the class' ExpandoMetaClass, as the example below shows.

Integer.metaClass.seconds = {return delegate * 1000}
Integer.metaClass.minutes = {return delegate * 1000 * 60}
Integer.metaClass.hours = {return delegate * 1000 * 60 * 60}
//test
assert 3.seconds() == 1000 * 3
assert 5.minutes() == 1000 * 60 * 5
assert 4.hours() == 1000 * 60 * 60 * 4

The above code gets Integer's metaclass (the ExpandoMetaClass) and adds methods by setting certain properties to closures. Here the name of the property is the name of the method we want to inject, and the closure represents the code that will be invoked when the method is called. Finally the 'delegate' in the closure in this context refers to the object on which we call the method.

The ExpanoMetaClass also has a DSL to make it simpler to add methods. The example above can be rewritten as follows, thus saving a few keystrokes.

Integer.metaClass {
seconds {return delegate * 1000}
minutes {return delegate * 1000 * 60}
hours {return delegate * 1000 * 60 * 60}
}

Sunday, April 12, 2009

What is metaprogramming?

The word metaprogramming keeps coming up everywhere in stuff I read nowadays. Even though I sort of knew what it meant I wasn't really sure. So I decided to ask the question 'what exactly is metaprogramming' on SO.

I got some really nice answers and links to articles. I have written this blog post as an effort to summarize what I have learned and to be able to share it with others who might be interested.

According to Wikipedia

''
Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. In many cases, this allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation."

The compiler is the simplest example of a metaprogram. It takes as input, code in some language, and creates code for another language. An example of metaprogramming in Java, is the use of generics. Here is a blog post I wrote (although for a different reason) some time back to show a simple example of how the compiler transforms Java code which has generics.

In languages like C and C++, metaprogramming can be done by the preprocessor.

In the Groovy programming language, there are two types of metaprogramming techniques: compile time metaprogramming, and runtime metaprogramming.

In compile time metaprogramming, Groovy allows us to hook into the compilation process at various stages, and modify the Abstract Syntax Tree which the compiler works on. (If you are interested, here is an Eclipse plugin to visualize the AST of a Java program)

An example of compile time metaprogramming is the use of the @Singleton annotation in Groovy. Whenever, we implement a Singleton, we always create a private constructor and a static method which gives us an instance of the Singleton. If we have several Singleton classes in our software, we have to implement this pattern for all of them. Using the @Singleton annotation gives us pattern reuse through AST transformations.

Let's say I want to create a Singleton class called MySingleton. In Groovy I can create it as follows without having to write a single line of plumbing code.


@Singleton class MySingleton {
//implementation of the class
}


During the compilation phase, some custom code will be invoked which will add the private constructor and a static instance() method to the class. Isn't this great? I think AST transformations can take reuse to a totally new level

Runtime metaprogramming can be done by using the Groovy MetaClass or more specifically the MetaObjectProtocol. Using the MetaClass, we can:
  • Add methods to objects at runtime
  • Determine if an object responds to a message or contains a property
  • Respond to calls made on non-existent methods
  • Respond to queries made on non-existent properties
Various builders in Groovy such as the MarkupBuilder and the SwingBuilder use the MetaObjectProtocol to achieve their magic. Here is some very simple code which uses SwingBuilder to create a simple GUI.


def swing = new SwingBuilder()
def gui = swing.frame(title:'GroovyTwitterClient',
size:[600,400],
defaultCloseOperation:WindowConstants.EXIT_ON_CLOSE) {
scrollPane {
tabbedPane = widget(new JTabbedPane())
}
}


What you see in the code above is a very simple DSL to create Swing GUI's. The code creates a JFrame, set's it's title, size, and defaultCloseOperation. Then it creates a JScrollPane and puts it in the JFrame. Finally it creates a JTabbedPane and puts it in the JScrollPane. If you look at the code carefully, you will realize that we call the method 'frame' on an instance of SwingBuilder and give it certain parameters and a closure. In the closure we call a method 'scrollPane' and give it another closure, and so on. Here each method call actually results in the creation of a Swing component. The parameters of the call are the properties which will be set on that component and the closure represents the component(s) to be added to that component. However, the most interesting thins is yet to come. The SwingBuilder class does not even have methods called 'frame', 'scollPane', and 'tabbedPane'. So then how does this work? The SwingBuilder class overrides invokeMethod(...) which is invoked for every single method call. So, when the 'frame' method is invoked on SwingBuilder, it goes through the MetaObjectProtocol to invokeMethod(...) . Here the call is intercepted and a swing component is created based on the name of the method.

This was just an overview. There is much more to metaprogramming and I will write more about it in future posts.

Thursday, April 09, 2009

Closures in lieu of inner classes in Groovy

Groovy does not support inner classes, at least not in version 1.6 . Having done Java coding for many years, I have become accustomed to using inner classes to encapsulate small related functionality, especially when it is needed for callbacks or some sort of configuration.

Now that I am learning Groovy, and writing a Twitter client, I needed to use inner classes, only to find out that Groovy does not support them. However, we can use closures and maps to simulate inner classes in Groovy. Before I explain this technique, I must say that it is simply a workaround, and at least in my opinion a not-so-good solution.

For this example I will show how I implemented a Jetty Handler using closures instead of an anonymous inner class. Jetty is a Java web server which supports Servlets and JSP's. I often use Jetty in my unit tests, because it can be started in-memory from an API call. Jetty can be configured in code with handlers, so that it will use these handlers to service a web request.

In the code below, I have created a simple unit test which makes a GET request and tests that the response is "Hello World". Offcourse this is a very trivial test, and would not be useful in production.

Here is the setUp() method from the test case, HelloWorldTest.groovy . I have not showed the entire test case for the sake of brevity.


Server _server //Jetty Server

@Override

public void setUp() {
//configure Jetty Server

_server = new Server(8080)

_server.setHandler(JettyHandlerFactory.getHelloWorldHandler())
_server.start()
}



We set the handler to mock HttpRequests in the call _server.setHandler() . The code below shows how JettyHandlerFactory.groovy uses closures instead of inner classes to implement the handler.


import org.mortbay.jetty.handler.AbstractHandler;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



public class JettyHandlerFactory{



public static AbstractHandler getHelloWorldHandler() {

//define the closure for a method of the inner class

def handle = { String target,

HttpServletRequest req,

HttpServletResponse res,

int dispatch ->

res.setContentType('text/html')

res.setStatus(HttpServletResponse.SC_OK)


def builder = new groovy.xml.MarkupBuilder(res.getWriter())

builder.html {

head {}

body('Hello World') {



}

}

req.setHandled(true)

}



//define a Map for the method name and closure

def handlerMethods = ['handle' : handle]

return handlerMethods as AbstractHandler

}


}




Because Groovy does not support anonymous inner classes, what we had to do was to create a closure called handle. This closure contains the that will be run when the handle method of the handler is invoked. The name of the closure does not necessarily have to be handle. It is names this just to increase readability.

Then we create a Map called handlerMethods to hold closures for all the methods we want to override in AbstractHandler. In this case we want to override just one method; handle. The keys in the Map must be strings which are named to the method names we want to override. The values must be the closures which implement the method. These closures must accept input parameters that the method accepts. The closure above accepts 4 input parameters.

Finally the class is created by converting the Map into a class using the
return handleMethods as AbstractHandler
invocation.

Tuesday, April 07, 2009

Sharpening the saw with online competitions

Some time back Jeff Atwood wrote about Sharpening the saw on his blog. He defines sharpening the saw as (which is rightfully attributed to Steven Covey):

Sharpening the saw is shorthand for anything you do that isn't programming, necessarily, but (theoretically) makes you a better programmer.

There are several things developers can do to sharpen their saw. One of them is participating in programming competitions. There are several websites which host online programming competitions, and I really like this concept. Participants can work on these competitions at a time of their convenience, and those who do not have "real world" competitions hosted in their cities and towns, can also participate.

Code Chef publishes online competitions which can be solved in any one of 35 programming languages. I like the fact that they give developers freedom to code in their favorite language. Many other online competitions do not give this freedom, and impose a particular programming languages on participants.

All the problems published thus far on Code Chef seem to be mathematical in nature. That's fine and also understandable. Such problems have a definite output and can be easily judged for correctness. It can be a bit difficult to objectively judge programs which are more design oriented.

My math skills have really depleted since high school, so I am looking forward not only to sharpening my saw but also my math skills.

Sunday, April 05, 2009

Groovy beans

A typical Java Bean is a Java class which is serializable, has a public no-arg constructor, private attributes, and getter/setter methods. I'd say this is a lot of stuff for a simple pojo.

Groovy beans did to pojo's what Java could not. They are actually simple. A typical Groovy bean needs to implement java.io.Serializable and add properties to it. We do not need to add any getters/setters, they are added automatically for us.

Here is a simple Groovy bean.


class Customer implements java.io.Serializable {
String firstName //will be a private attribute in the bytecode
String lastName //will be a private attribute
def middleInitial //beans can even contain dynamic properties
}


See.... Groovy beans do not have any getters or setters, and you will also have noticed that the fields are not private. Even though the source does not contain getter/setter methods and private attributes, the bytecode does. When this bean is converted into bytecode all attributes which do not have an access modifier will be treated as properties. What this means is, they will become private attributes and public getter/setter methods will be generated for them.

Now let's create an instance of this bean.


def customer = new Customer()
//Even though this looks like we are accessing public fields
//the bytecode actually invokes the setter methods of these properties
customer.firstName = "John"
customer.lastName = "Gardner"
customer.middleInitial = "U"
println 'Customer's Last Name: ' + customer.lastName


Creating an instance of a Groovy bean is very similar to Java, but assigning values to it's properties seems to be a bit different. When we assign the value "John" to firstName, it seems as if we are assigning a value to a public field. But this is not what happens. Internally Groovy converts this into a call to the setter method for that field. Thus we get the same end result as in Java, but with less verbosity.

We can also use the bean constructor to instantiate and initialize the bean together.


def customer1 = new Customer(firstName: "Bob",
lastName: "Steele",
middleInitial: "Z")


In the above code this is what really happens under the hoods. First the constructor is invoked, followed by calls to the corresponding setter methods.

This is wonderful. Groovy Beans are just like Java Beans, but much simpler and smaller.

Now, you must be thinking, but what if I want to add custom code to the getter or setter? That is simple, simply create your own getter or setter and Groovy will use your code instead of automatically generating it's getter or setter. Your getter/setter can either be public or even protected if you so wish.

But what if we want to create a simple field without getters and setters. How do we prevent Groovy from automatically inserting getter/setters in the bytecode. Again simply create a field and give it an access modifier (like 'private') and Groovy will not auto generate anything for you.

One question that comes to mind, is how do we create package private attributes? Since Groovy 1.6, a package private field can be created by annotating it with @PackageScope

Thursday, April 02, 2009

Control structures in Groovy

To control program flow in Groovy we can use all control structures available in Java, but with additional power.

In Java, branching statements like 'if', and 'while' accept an expression which evaluates to a boolean value. We cannot use an object where a boolean is required. Groovy, on the other hand has the concept of Groovy truth, which coerces non boolean values into boolean values. Thus statement like these are perfectly valid in Groovy.
List list = ['apples']
if(list) {
println 'This list is not empty'
}
Here the list object evaluates to a boolean value. Any non empty list will evaluate to true. This article explains coercion rules for the Groovy truth.

Groovy truth allows us to use non booleans inside conditionals. It evaluates objects to their (truth) boolean values. With Groovy truth we can use booleans, Strings, GStrings, List, Map, Numbers, and any arbitrary object where a boolean is expected.

Groovy also gives greater power to switch statements. In Java we can only use integers, characters, and Enum constants in switch statements. However, Groovy allows the use of expressions that evaluate to arbitrary objects in switch as well as case statements.


printGameType('Soccer')
printGameType('Cricket')
printGameType('Tag')

def printGameType(name) {
def boardGames = ['Chess', 'Carrom', 'Monopoly']
def ballGames = ['Soccer', 'Football', 'Basketball']
def ballAndBatGame = ['Baseball', 'Cricket']
switch(name) {
case boardGames:
println """${name} is a board game"""
break
case ballGames:
println """${name} is a ball game"""
break
case ballAndBatGame:
println """${name} is a ball and bat game"""
default:
println """Could not determine game type of ${name}"""
}
}


The output from running the above program is:


Soccer is a ball game
Cricket is a ball and bat game
Could not determine game type of Cricket
Could not determine game type of Tag


In Groovy, whenever a case expression is evaluated, the isCase() method of the object (which the case expression evaluates to) is invoked with the object provided in the switch statement as a parameter. In the above example, the isCase() method of each of the List objects is invoked with the String provided in the switch statement. If an object does not have an isCase() method then it's equals() method is invoked.

These new features makes Groovy a very expressive language to represent control logic.

Wednesday, April 01, 2009

Groovy Maps

Using Maps in Groovy is much simpler than in Java. Some key differences are:

  • Map declaration and instantiation are simpler

  • Elements of a Map can be accessed either using the bean style or array style

  • Iterating across Maps is far less verbose in Groovy than in Java



The code sample below is self explanatory



//Declaring and instantiating a Map
def emptyMap = [:]


//Populating a Map
//Notice that the keys which are strings are not
//enclosed within quotes
def population = [Estonia:1299371,
Finland:5250275,
Honduras:7792854,
HongKong:7055071]

//Non string keys must be enclosed in ()
def numbers = [(Integer.valueOf("1")):"One",
(Integer.valueOf("2")):"Two"]


//Accessing Map elements
//Maps can be accessed using bean style and
//array style notations respectively
println "Estonia population: " + population.Estonia
println "Finland population: " + population['Finland']
//Use default values in case key does not exist (if key does not exist, then
//it will be added with the default value)
println "Spain population: " + population.get("Spain", 40525002)

//Iterating over all the entries in a Map
println "Population stats"
population.each { key, value ->
println key + " : " + value
}

println "Numbers as words"
numbers.each() {
println it.key + ":" + it.value
}

//Search within a Map
println 'Countries with a population greater than 1 million'
result = population.findAll {key, value ->
value > 5000000
}
println 'population > 5000000 ' + result.keySet()



Output from running the above program:


Estonia population: 1299371
Finland population: 5250275
Spain population: 40525002
Population stats
Estonia : 1299371
Finland : 5250275
Honduras : 7792854
HongKong : 7055071
Spain : 40525002
Numbers as words
1:One
2:Two
Countries with a population greater than 1 million
population > 5000000 ["HongKong", "Finland", "Spain", "Honduras"]