Search code examples
rubyooppojo

Plain Old Objects in Ruby?


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?


Solution

  • 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