When to use nested classes and classes nested in modules?

cmhobbs picture cmhobbs · Jun 1, 2011 · Viewed 71.7k times · Source

I'm pretty familiar with when to use subclasses and modules, but more recently I've been seeing nested classes like this:

class Foo
  class Bar
    # do some useful things
  end
end

As well as classes nested in modules like so:

module Baz
  class Quux
    # more code
  end
end

Either documentation and articles are sparse or I'm not educated on the subject enough to grope for the right search terms, but I can't seem to locate much information on the topic.

Could somebody provide examples or links to posts on why/when those techniques would be used?

Answer

Pan Thomakos picture Pan Thomakos · Jun 1, 2011

Other OOP languages have inner classes which cannot be instantiated without being bound to an upper level class. For instance, in Java,

class Car {
    class Wheel { }
}

only methods in the Car class can create Wheels.

Ruby doesn’t have that behaviour.

In Ruby,

class Car
  class Wheel
  end
end

differs from

class Car
end

class Wheel
end

only in the name of the class Wheel vs. Car::Wheel. This difference in name can make explicit to programmers that the Car::Wheel class can only represent a car wheel, as opposed to a general wheel. Nesting class definitions in Ruby is a matter of preference, but it serves a purpose in the sense that it more strongly enforces a contract between the two classes and in doing so conveys more information about them and their uses.

But to the Ruby interpreter, it’s only a difference in name.

As for your second observation, classes nested inside of modules are generally used to namespace the classes. For instance:

module ActiveRecord
  class Base
  end
end

differs from

module ActionMailer
  class Base
  end
end

Although this is not the only use of classes nested inside of modules, it is generally the most common.