Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to approach abstract class solution with Ruby?

I know abstract classes are not a feature in Ruby, and surely there is a philosophic reason behind that, but I would like to know if there is way to approach problems that typically are resolved using abstract classes in other languages like C++ and Java.

For example: I need three classes Triangle, Square, and Circle. Because these are all geometric figures, I was thinking in coding an abstract class called AbstractFigure with an abstract method get_area, which would be implemented by the concrete classes Triangle, Square, and Circle.

How can I do this following Ruby philosophy?

like image 742
Crixx93 Avatar asked Feb 20 '16 20:02

Crixx93


1 Answers

You're right that it doesn't exist as a well defined concept in ruby, unlike other languages like Java where it's used heavily.

But you're also right that there's plenty of situations that warrant it.

Here's how I've gone about it, with your example -

class AbstractShape
  attr_accessor :edges

  def initialize
    # ...
  end

  def get_area
    raise NoMethodError("Override this implementation")
  end
end


class Square < AbstractShape
   def initialize
     # square-specific stuff
     super
   end

   def get_area
     self.edges * foo * bar
   end
end

The key is to define all the available methods at the top level for readability and consistency, but make sure they raise an error if used.

If there is a method that you are absolutely sure will be used consistently the same way across all shapes, then define it in AbstractShape

The attr_accessor will also inherit, so you'll have @edges available on a per instance basis for each shape. But you can still have methods within the AbstractShape class that reference @edges, because they'll just use the correct local instance variable.

like image 51
user2490003 Avatar answered Sep 20 '22 01:09

user2490003