liveBook · Manning

Functional, stateless philosophy

As explained in The Well-Grounded Rubyist, Fourth Edition

A functional language is a programming language that emphasizes computation through functions and minimizes mutable state and side effects.

Functional programming emphasizes computation through functions while minimizing mutable state and side effects. Ruby supports this style without guaranteeing immutability or referential transparency, so functional and object-oriented approaches can coexist. section 16.0

A functional approach favors:

  • Pure functions that return the same result for the same arguments without side effects. section 16.1
  • New values instead of changing existing state where practical. section 16.1
  • Attention to side effects beyond mutation: an unhandled exception can also interrupt a program unexpectedly. section 16.1.3
  • Reusable functions and lazy evaluation to work with large or infinite sequences. section 16.4.1

Make a new value instead of reassigning

Rather than incrementing num with `num = num + 1`, keep the original and assign the result to `new_num = num + 1`. Both are valid Ruby, but the latter avoids changing the existing variable's value. section 16.1

Table 16.1 Properties of functional and object-oriented programming styles

Property

Object-oriented

Functional

Promotes code reuse

√

√

Models behavior with objects

√

Separates data and behavior

√

Promotes encapsulation

√

√

Terse code

√

Generic routines

√

Modularity

√

Flexibility with polymorphism

√

Compare functional and object-oriented styles across reuse, encapsulation, modularity, and other properties. section 16.0

Functional techniques do not eliminate every side effect: useful programs may need to persist data, print output, or update a view. Choose between styles—or combine them—according to the trade-offs. section 16.1.3 section 16.0

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines pure functions and referential transparency, then illustrates mutation, exceptions, currying, and lazy sequences without deep mathematical treatment.
Examples
Contrasts reassigning an incremented variable with creating a new one, and demonstrates curried functions and lazy infinite sequences.
What you can do after
Apply currying and lazy enumerators to create reusable functions that process finite portions of infinite sequences.
How it connects
Connects functional programming to pure functions, referential transparency, immutability, side effects, currying, lazy evaluation, and object-oriented programming.

Also explained in

Compare how 19 books explain functional, stateless philosophy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.