The Java snippet below came from some vendor training we did recently. Although it’s just training code I thought it would be interesting to compare how the same thing could be done in (J)Ruby.
The most obvious difference is the verbosity - and so the overall length - of the Java code. There is a lot redundancy here and unfortunately the interfaces do not lend themselves to factoring it out. If PaymentMethodIF, TroubleTicketStatusIF and LineTypeIF all had a common ancestor it would be easy to create a ‘printDetails’ method and call it for each. But they don’t so each one ended up with it’s own ‘for’ loop to do the printing. Yuck.
With Ruby this limitation is gone, so I was able to loop through, dynamically generate the method name and call it using reflection.
I found the other big productivity booster was using (j)irb to interactively invoke the Java methods. Without the need to compile in between code changes the trial and error discovery went much faster.
Java version:
public static void main(String[] args) {
PaymentMethodIF[] pmIf = ObjectRefMgr.getAllPaymentMethods();
for (int i = 0; i < pmIf.length; i++) {
System.out.println(pmIf[i].getClass().getName() + " - " + pmIf[i].getName());
}
TroubleTicketStatusIF[] ttsIF = ObjectRefMgr.getAllTroubleStatuses();
for (int i = 0; i < ttsIF.length; i++) {
System.out.println(ttsIF[i].getClass().getName() + " - " + ttsIF[i].getName());
}
LineTypeIF[] ltIF = ObjectRefMgr.getAllLineTypes();
for (int i = 0; i < ltIF.length; i++) {
System.out.println(ltIF[i].getClass().getName() + " - " + ltIF[i].getName());
}
}
JRuby version:
['PaymentMethods', 'TroubleStatuses', 'LineTypes'].each do |method_suffix|
method_name = "getAll" + method_suffix
resultArray = ObjectRefMgr.send(method_name)
resultArray.each {|result| puts "#{result.class} - #{result.getName()}"}
end