Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

ruby - When to use nested classes and classes nested in modules?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...