Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plain Old Objects in Ruby?

Tags:

oop

ruby

pojo

I notice in Ruby it is very common to for vendor APIs to pass back results as arrays? Shouldn't Plain Old Objects (Like POJOs in Java) be more of a standard? If I write my own library shouldn't I use POJOs POROs?

like image 791
Zombies Avatar asked Feb 12 '10 13:02

Zombies


2 Answers

I think array vs object is a false dichotomy.

It is perfectly reasonable, where an API call is returning more than one of a thing, that it is in the form of an array (and an array is a fairly simple object, and therefore arguably a 'PORO', in Ruby anyway)

Edit: in response to your comments:

The example you cite ( http://github.com/cjheath/geoip ) returns an array of differing items. I agree this is not necessarily the best format to return the data in. In that case I would have thought a hash with sensibly named keys would be a better structure.

As John Topley says, the OO nature of Ruby means people don't have to invent such terminology as 'PORO', as a hash is pretty much as simple as you can get.

like image 171
DanSingerman Avatar answered Sep 30 '22 09:09

DanSingerman


It's all objects, all the time. The key is whether the objects being returned have behavior associated with them. It's fine to do this:

  def read_first_and_last_name(data_source)
    [data_source.read_string, data_source.read_string]
  end

But the moment you find there is behavior associated with those data items...

  def print_name(first_name, last_name)
    puts "#{first_name} #{last_name}"
  end

  def read_and_print_name
    first_name, last_name = read_first_and_last_name(data_source)
    print_name(first_name, last_name)
  end

...then they should be a class:

  class FullName

    def FullName.read(data_source)
      FullName.new(data_source.read_string, data_source.read_strng)
    end

    def initialize(first_name, last_name)
      @first_name = first_name
      @last_name = last_name
    end

    def print
      puts "#{@first_name} #{@last_name}"
    end

  end

With a name's behavior nicely encapsulated, usage becomes as simple as:

  def read_and_print_name
    FullName.read(data_source).print
  end
like image 20
Wayne Conrad Avatar answered Sep 30 '22 10:09

Wayne Conrad