开发者

What are the principal differences in domain modelling in .NET/Java versus Ruby?

I'm an experienced .NET developer (6 years) and I'm really getting into (non-anemic) domain modelling: aggregate roots, putting invariants in constructor parameters, more methods, less public classes and members.

I was showing my Rubyist coworker (a developer I really respect) what I've been working on and he indicated that much of the text on the screen would be necessary in Ruby, but I didn't understand exactly what he meant. So my question is this:

For an app sufficientl开发者_StackOverflowy complex that a domain model is really called for, what are the principal differences between the domain model implemented in a strongly-typed, enterprise-y platform like .NET/J2EE versus the same model implemented in Ruby (in The Ruby Way)? Is Ruby a well-suited tool for this sort of problem?


Strongly typed vs not does, in my opinion, not make much difference to the amount of code. I do a lot of complex domain models in javascript, and you can't really take advantage of loose typing and maintain sane code. Typically you should keep type of an instance field the same, not have an object sometimes and array other times - mixing apples and pears just confuses yourself and others.

The one time it may be appropriate is in methods taking different arguments. Javascript has not method overloading, so accepting both apples and pears may be appropriate.

What your friend might have meant with ruby is the terse syntax for declaring classes. All instance fields in ruby are private - and there's a short hand syntax for declaring getters and setters, comparators, etc. Compare:

Ruby

class Person
  attr_reader :name, :age
  attr_writer :name, :age
  def initialize(name, age)
    @name, @age = name, age
  end
  def <=>(person) # Comparison operator for sorting
    @age <=> person.age
  end
  def to_s
    "#@name (#@age)"
  end
end

Java

public class Person implements Comparable<Person> {
    private String name;
    private int age;
    public Person(String name, int age) {
      this.name = name;
      this.age = age;
    }
    public int compareTo(Person other) {
       return this.age - other.getAge();
    }
    public String getName() {
      return name;
    }
    public void setName(String name) {
       this.name = name;
    }
    public int getAge() {
      return age;
    }
    public void setAge(int age) {
      this.age = age;
    }
    public String toString() {
      return name + " ("+age+")";
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜