8

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?

2
  • 4
    Just create a base class and don't instantiate it. Looks good enough to me. :) Commented Feb 20, 2016 at 20:35
  • Remember Ruby is dynamically typed, so you don’t even need a base class – just three classes that all have get_area method. Commented Feb 20, 2016 at 20:51

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Perhaps note a)AbstractShape can have mix of methods, some of which are inherited and others, as above, which force the same method to be defined in a subclass; and b) to prevent AbstractShape from being instantiated one could give it the method def initialize; raise "Cannot instantiate class AbstractShape" if self.class == AbstractShape; ... ;end.
7

Define a normal class AbstractFigure with a method get_area that just raises NotImplementedError. Then each derived class overrides the get_area method with it's own implementation.

class AbstractFigure def get_area raise NotImplementedError.new( 'appropriate error message' ) end end class Square < AbstractFigure def get_area # implementation here end end 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.