Ruby And The Seven Virtues

Geplaatst door Michiel de Mare ma, 11 feb 2008 08:52:00 GMT

This is a Dutch blog, and therefore we love to quote Dutch computer scientists:

Elegance is not a dispensable luxury but a factor that decides between success and failure.

Edsgar Dijkstra

Seven pieces of Java code and the alternative in Ruby:

1. Short circuit with nil

Java


if(foo != null) { 
  bar(foo); 
} else { 
  bar(""); 
}

Ruby


bar(foo || "")

2. String array notation

Java


String[] weekdays = new String[] { "Monday", 
    "Tuesday", "Wednesday", "Thursday", "Friday", 
    "Saturday", "Sunday" }

Ruby


weekdays = %w( Monday Tuesday Wednesday Thursday 
    Friday Saturday Sunday )

3. Cutting away repetitions

Java


ContactPerson prev,next;
prev = employeeService.browseContact(currentId, false);
if(prev != null) {
  ctx.setAttribute("previous", prev.getId());
}
next = employeeService.browseContact(currentId, true);
if(next != null) {
  ctx.setAttribute("next", next.getId());
}

Ruby


lmb = lambda do |flag,dir| 
  cp = employeeService.browseContact(currentId, flag)
  ctx[dir] = cp.id if cp
end
lmb[false, "previous"]
lmb[true, "next"]

4. Class with two attributes

Java


public class T {
  private String name;
  private int value;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getValue() {
    return value;
  }

  public void setValue(int value) {
    this.value = value;
  }
}

Ruby


class T
  attr_accessor :name, :value
end

5.Convert an array of dates into an array of strings

Java


SimpleDateFormat dateFormat;
dateFormat = new SimpleDateFormat("MM-dd-yyyy");
String[] s = new String[dates.length];
for(int i = 0; i < dates.length; i++) {
  s[i] = dateFormat.format(dates[i]);
}

Ruby


dates.map {|d| d.strftime '%m-%d-%Y' }

6. Convert a string into an integer, return 0 in case of failure.

Java


long l = 0;
if(s != null) {
  try {
    l = Long.parseLong(s);
  } catch(NumberFormatException ex) {
  }
}

Ruby


l = (s || 0).to_i

7. Throw exception if condition is false for at least one element.

Java


boolean orderByOK = false;
for (int i = 0; i < ORDER_COLUMNS.length; i++) {
  if (ORDER_COLUMNS[i].toUpper().equals(col)) {
    orderByOK = true;
    break;
  }
}
if (!orderByOK) {
  throw new IllegalArgumentException(col);
}

Ruby


unless ORDER_COLUMNS.any? {|c| c.upcase == col}
  raise "IllegalArgument: #{col}" 
end

Geplaatst in ,  | 1 reactie

Reacties

  1. Robert zei 7 dagen later:

    I’m not a Java fanboy (actually prefer Ruby mostly), but still—please use the simpler Java idioms to make the code more comparable.

    Example:

    1: bar(foo != null ? foo : ””)

    2: String[] weekdays = “Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday”.split(”,”);

    6: long l = 0; try { l = Long.parseLong(s); } catch(Exception ex) { }

(Laat url/e-mail achter »)

   Voorvertoning