Skip to main content

Posts

Showing posts from April, 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

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

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

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 Fr

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); } }

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

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 som

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

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 program

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 ha

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 sta

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: &quo