Basics

Crystal Modules

Using Crystal Modules

Crystal modules use module for code organization and reuse.

Introduction to Crystal Modules

In Crystal, modules are a mechanism for organizing and reusing code. Similar to classes, modules allow you to define methods, constants, and other modules. However, unlike classes, modules cannot be instantiated or inherited. Instead, they serve as containers for grouping related methods and constants, which can be included in classes or other modules.

Defining a Module

Defining a module in Crystal is straightforward. You use the module keyword followed by the module name. All methods and constants defined inside the module are accessible through the module name or can be included in classes or other modules.

Including Modules in Classes

One of the primary uses of modules is to include their functionality in classes. This is done using the include keyword. By including a module, a class can access the methods and constants defined in that module.

Mixins and Code Reuse

Modules in Crystal can be used as mixins, a powerful feature that allows for code reuse across multiple classes. By defining common functionality in a module, you can include it in any number of classes, promoting DRY (Don't Repeat Yourself) principles.

Namespaces with Modules

Modules also serve as namespaces, which help to avoid name clashes by encapsulating constants, methods, and other modules. This is particularly useful when your program grows larger, and you need to manage multiple components that might otherwise conflict with each other.

Conclusion

Crystal modules are a powerful tool for code organization and reuse. By leveraging modules, you can create reusable components, encapsulate functionality, and maintain a clean and organized codebase. Whether you're using them for mixins, namespaces, or both, modules are an essential part of Crystal programming.