5 Rules for writing object-oriented code
My notes from a Ruby talk from 2013 by Sandi Metz.
What are rules?
- taboos
- laws
- norms (customs), group-held beliefs
- many of are arbitrary and not enforcible
- why do we follow rules? obedience? self-interest, identity/status, authority, order, social sanctions, ignorance, habit
5 Constraints
- No more than 100 lines per class
- No more than 5 lines per method
- No more than 4 parameters per method
- No more than 1 instance variable per view
- No more than 2 class names per controller/action (a Rails-specific rule)
Why?
- bias towards small objects (POROs = plain old Ruby objects)
- bias away from dependencies
- the rules are a means to an end: consistent goals
- design choice of small objects
- objects vs. procedures
- the entire applications is harder to understand, but you don’t need to understand the whole app — you only need to understand the part you want to change
- following the rules might be in your self-interest
Other benefits of rules
- signal others
- bias to collaboration
- the belief in some rules and the willingness and self-discipline to follow them
- you can break the rules only under the supervision of trustworthy humans