RUBY / CHAPTER 09

Objects with small behavior contracts

Advanced

Compose behavior through methods and modules.

By the end of this chapter

  • Use instance state deliberately
  • Share behavior through a module
  • Depend on required methods rather than concrete classes

The idea

Ruby objects combine state with methods that operate on it. Instance variables belong to an individual object, while a class describes how new instances behave. Keep state private when callers should request operations instead of directly changing fields. A small public surface helps maintain invariants, such as a counter never decreasing or a record keeping a stable identifier.

A module can supply reusable methods without requiring a single inheritance hierarchy. Duck typing means code often depends on an object supporting the needed methods rather than having a particular class name. Make that expected behavior explicit in documentation and tests. Composition is useful when an object delegates a task to another collaborator, allowing a test implementation to be supplied without changing the caller.

Ruby example
module Named
  def label
    "Item #{@name}"
  end
end

class Card
  include Named
  def initialize(name)
    @name = name
  end
end

puts Card.new("A").label
Result
Item A

The included module supplies label as an instance method. The method uses the instance variable initialized separately for each Card.

Try it yourself

Create a formatter object and a report object that accepts any collaborator providing format(value).

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

A function needs an object that responds to write(text). What is the most flexible contract?