Single Responsibility

Episode Summary

This week we talk about creating classes, why single responsibility matters, and writing code that embraces change.

Episode Notes

Chapter 2: Designing Classes with a Single Responsibility

The foundation of an object-oriented system is the message, but the most visible organizational structure is the class

Questions to ask yourself:

Creating Classes That Have a Single Responsibility

A class should do the smallest possible useful thing; that is, it should have a single responsibility

An Example Application: Bicycles and Gears

Small Gears

Large Gears

see 1_gear.rb

see 2_gear.rb

Why Single Responsibility matters

Determining If a Class Has a Single Responsibility

When to Make Design Decisions

Write Code That Embraces Change

Here are some techniques that help you write code that embraces change

Depend on Behavior, Not Data

Hide Instance Variables

Hide Data Structures

see 3_obscuring_references.rb

see 4_revealing_references.rb

Enforce Single Responsibility Everywhere

Extra Extra Responsibilities from Methods

def diameters
  wheels.collect { |wheel| wheel.rim + (wheel.tire * 2) }

Finally, the Real Wheel

see 5_gear_and_wheel.rb