Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Patterns > Including Modules versus Opening Classes

Including Modules versus Opening Classes

You can use modules to collect a set of related definitions into a single namespace, enhancing code modularity. Modules also form the basis for programming mix-ins: Common functionality of a set of classes can be extracted into a module, which then can be included in the original classes. This can help to avoid code duplication and, in general, improves program design.

Using modules as a structuring mechanism has a (albeit small) performance impact: Resolving a method (or constant) name included via a mix-in module takes more time than resolving a name defined directly inside a class. If n modules are included in a class, the interpreter will need n/2hash lookups on average to find the method, unless the (method id, scope) pair can be found in Ruby’s method cache.[13] Therefore, if a module gets included in only one other class (or module), it’s preferable to open the class instead.

[13] This makes measuring the performance impact with a small test program difficult because Ruby’s method lookup cache is very effective for such programs.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial