Code Like Zell

A cheap abstract class in Ruby

Posted 29 March 2009.

When I create a class that I don’t want to be instantiated, I use the following pattern:

  class MakeMeAbstract
    def initialize
      raise "Don't instantiate me!" if abstract_class?
      puts "Instantiated!"
    end
    private
    def abstract_class?
      self.class == MakeMeAbstract
    end
  end

It can’t be instantiated:

  MakeMeAbstract.new rescue puts "I'm abstract"   # => "I'm abstract"

But it can be subclassed, and the subclass can be instantiated:

  class Child < MakeMeAbstract
  end
  Child.new   # => "Instantiated!"

This is a learning experience for me. When subclassing an abstract class I wonder if it would be better to use a mixin instead: I could overwrite mixed in methods just as easily as methods in a parent class. The structure changes from this:

  class Bar
    def status
      print "is full"
    end
  end
  class WetBar < Bar
    def status
      print "is wet, "
      super
    end
  end
  wet_bar = WetBar.new
  wet_bar.status    # => "is wet, is full"

To this:

  module Bar
    def status
      print "is full"
    end
  end
  class WetBar
    include Bar
    def status
      print "is wet, "
      super
    end
  end
  wet_bar = WetBar.new
  wet_bar.status    # => "is wet, is full"

Input is welcome in the comments.

All CLZ Posts

Hide this
Joypad Banner