Seeing as I've done a slightly better version of the Python code for a previous article, I wouldn't want to seem to be biased, so here's the same approach used for the corresponding Java code.
Whether you think this is better or not, or if you'd prefer it different in some other way, is something you'd be able to tell me if we were pairing. I have to admit that at this point, having made these changes, I now also think that it would have been better to do TDD after all, as, although it wouldn't have been faster in this case, the code might well have been better. Doing this TDD, or pairing, is left as an exercise for the interested reader.
package com.oocode;
import java.io.*;
import java.util.*;
public class Graph2Csv {
private Map<String, Node> nodes = new HashMap<String, Node>();
public static void main (String[] args) throws IOException {
new Graph2Csv().run();
}
private void run() throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String line = input.readLine();
while(line != null){
if(line.contains(" -> ")){
String[] parts = line.split(" -> ");
String source = parts[0];
String destination = parts[1].substring(0,parts[1].length()-1);
node(destination).incoming++;
node(source).outgoing++;
}
line = input.readLine();
}
System.out.println("incoming,node name,outgoing");
for(Node node : nodes.values()){
System.out.println(node.incoming+","+node.name+","+node.outgoing);
}
}
private Node node(String nodeName) {
if(!nodes.containsKey(nodeName)){
nodes.put(nodeName, new Node(nodeName));
}
return nodes.get(nodeName);
}
private class Node{
public Node(String nodeName) {
this.name = nodeName;
}
public int incoming,outgoing;
public String name;
}
}
Posted by ivan at February 12, 2006 6:18 PM
Hi Ivan,
An interesting experiment comparing the two languages. Just to add to your fun I've posted an implementation of this code in Groovy, so you can compare and contrast. Heck, maybe I can encourage you to come over to http://groovy.codehaus.org and help out ;-)
Here's the Groovy version of your code:
http://javanicus.com/groovy/Graph2Csv.groovy.html
cheers,
Jez.
isn't substring(0,parts[1].length()-1) a noop?
Posted by: John Wilson at February 23, 2006 3:56 PM