4 Data abstractions

 

This chapter covers

  • Abstracting with modules
  • Working with hierarchical data
  • Polymorphism with protocols

This chapter deals with building higher-level data structures. In any complex system, there will be a need for abstractions such as Money, Date, Employee, and OrderItem, all textbook examples of higher-level abstractions that usually aren’t directly supported by the language and are instead written on top of built-in types.

In Elixir, such abstractions are implemented with pure, stateless modules. In this chapter, you’ll learn how to create and work with your own data abstractions.

In a typical OO language, the basic abstraction building blocks are classes and objects. For example, there may be a String class that implements various string operations. Each string is then an instance of that class and can be manipulated by calling methods, as the following Ruby snippet illustrates:

"a string".upcase

This approach generally isn’t used in Elixir. Being a functional language, Elixir promotes decoupling of data from the code. Instead of classes, you use modules, which are collections of functions. Instead of calling methods on objects, you explicitly call module functions and provide input data via arguments. The following snippet shows the Elixir way of uppercasing a string:

String.upcase("a string")

4.1 Abstracting with modules

4.1.1 Basic abstraction

4.1.2 Composing abstractions

4.1.3 Structuring data with maps

4.1.4 Abstracting with structs

4.1.5 Data transparency

4.2 Working with hierarchical data

4.2.1 Generating IDs

4.2.2 Updating entries

4.2.3 Immutable hierarchical updates

4.2.4 Iterative updates

4.2.5 Exercise: importing from a file

4.3 Polymorphism with protocols

4.3.1 Protocol basics

4.3.2 Implementing a protocol

4.3.3 Built-in protocols

Summary