Thursday, February 23, 2006

Ruby 0.0

Today I decided to take some time and have a look at Ruby. I found online a version of Programming Ruby and started reading it. In fact I knew I was going to like Ruby. In fact the first time I took contact with it I quite liked it, even if I didn't fully exploit its capabilities.

Well... let's see how it goes. Right at the moment the first thing I wrote is:

class Employee
    attr_reader :wage, :name
    attr_writer :wage
    def initialize(name, surname, wage)
        @name = name
        @surname = surname
        @wage = wage
    end
    def surname
        @surname
    end
    def to_s  
        "#{name} #{surname} (#{wage})"
    end
    protected :wage=
end

class Manager > Employee
    def initialize(name, surname, wage, employees=[])
        super(name, surname, wage)
        @employees = employees
    end
    def setWage(emp, wage)
        emp.wage = wage
        emp
    end
    def to_s
        super + @employees.collect{|e| "\n  #{e}"}.join("")
    end
end
mr = Employee.new("Jack", "Bravo", "1000€")
mc = Employee.new("Michael", "Charlie", "300€")
mngr = Manager.new("Angus", "Smith", "10000€", [mr, mc])
mngr.setWage(mc, "700€")
puts mngr

This post has been recently re-edit to test SyntaxHighliter.
Moreover, I want to stress that the design would be terrible.

People are *not* Employees or Managers. Their *role* is Employee or Manager.
This is a case when favouring inheritance over composition? is wrong.
More on this later!

No comments: