Newsletter:

(Article) Java developers should learn Ruby

Article : Java developers should learn Ruby

Learning another language forces you to dive into a different community. You'll find different ideas and different approaches to many of the same problems. They may not be better ideas and approaches, just different. Other communities often have a fresh perspective on similar problems. And sometimes it will even make you appreciate what we really do have in the Java community (like a huge number of really great libraries).

Learning another language can teach you new idioms. Some you may be able to use in Java, and others you won't. Ruby blocks, for example, are Ruby's form of closures and are widely used in most Ruby programs. They're extremely useful for running predefined code that delegates (perhaps repeatedly) to the block for custom behavior. Here's a simple example of iterating over an array and doing some custom behavior (printing the element):

animals = ['lion','tiger', 'bear']
animals.each {|animal| puts animal }

Unfortunately, Java doesn't have closures. Not really. The closest thing in Java 6 is to pass an anonymous inner class in much the same way that listeners are often used in GUI applications. All we need is a predefined interface and a method on a class that accepts the implementation and that performs the iteration (like the "each" method in Ruby). So pretend that java.util.List has an "each" method that takes an implementation of an OnEach:

public interface OnEach<T> {
void run(T obj);
}
public interface List<T> ... {
void each( OnEach<T> action );
}

Then our example would look something like this:

List<String> animals = Arrays.asList( new String[]{"lion", "tiger", "bear"} );
animals.each( new OnEach<String>() {
public void run( String animal ) {
System.out.println(animal);
}
});

Kinda gross, huh? But even though it's not as easily done, it's a pattern that you can use in your designs to allow custom behaviors without requiring subclasses. There are several closure proposals for Java 7, but none are as easy as in Ruby or JavaScript. By the way, Alex has the best resource for all things Java 7.
[Read More...]

Courtesy:- http://www.jboss.org/