Writing Modular Programs
Elixir's module system allows us to define layers of related functions. In this part of the course, we'll explore the concepts of modules, and the ability to reference code in one module from another.
-
Writing Modular ProgramsWelcome Back
We'll recap the ground we covered in day 1 of this training, so it's fresh in your mind, as we continue building up toward Elixir proficiency!
-
Writing Modular ProgramsModules & Three Important Directives
Modules are just a group of several functions, some of which may be private and some of which may be public. Modules give us the ability to define named functions using the
def
macro, which offer a few other features that were unavailable in the world of anonymous functions. -
Writing Modular ProgramsEXERCISE: Mission Control
We've got a set of tests for a couple of Elixir modules that are used to control a space ship. Alter the code to make the unit tests pass, and ensure that you've kept as much of each module's internal functionality private as possible.
-
Writing Modular ProgramsBasic Metaprogramming
While the
use
macro is not strictly a directive, it's of particular importance when considering "mixins" for common functionality, shared across multiple concrete modules. -
Writing Modular ProgramsEXERCISE: Extending a Module
The
use
macro can essentially be used to decorate a module with some code from another module. -
Writing Modular ProgramsProtocols & Behaviors
Protocols are a mechanism for polymorphism in Elixir, where an implementation of a certain contract is defined on a per-type basis. In other languages, this contract would be called an interface (Java), or a pure abstract class (C++)
Under the hood, part of how this works is by way of a Behavior: a definition of a set of functions that modules who adopt this behavior must implement.
-
Writing Modular ProgramsEXERCISE: Serializer Protocol
Given a list of values, we want to be able to generate a string representation, either in CSV or JSON array format. Design a protocol, and adopt that behavior in each of two modules:
CSVSerializer
andJSONSerializer
. -
Writing Modular ProgramsLunch
Break for Lunch