class: center, middle
Slides available at ???????
class: center, middle
- single responsibility
- tell don't ask
- "law" of demeter
- Group logic
- Set boundaries
- Reuse code
- Easily find the parts (one) you need to modify / reuse
- Abstract complex concepts
class: center, middle
Tell an object what to do, don't ask about its state
class Dude
def have_coffee
@barista.status = :making_coffee
@barista.hand << 'filter handle'
@barista.hand << @barista.grinder.coffee
@barista.coffee_machine << @barista.hand # => BaristaPissedOffError:
# [...]
drink!
end
end
The logic (knowledge) belongs to the Barista
class Dude
def have_coffee
coffee = barista.get_coffee(:cappuccino)
drink!(coffee)
end
end
- Keep the logic in one place
- Find it no time
- Change it one place
- Don't break other code
- Happily move on...
class: center, middle
class: center, middle
Don't talk to strangers
class Person
def name ;end
def father ;end
def children ;end
def games ;end
end
class House
has_one :garden
end
jeff_buckley.father.name.to_s.titleize.to_a # => ['Tim Buckley']
house.garden.tree.class.name # => Sicomoro
person.map(&:children).map(&:games).flatten.each(&:destroy)
What's familiar?
- Same class
- Language
- Framework
Unconvinced?
class Booking
has_one :room
end
class Room
def price ;end
end
booking.room.price # preview
booking.room.price # confirmation page
booking.room.price # email
booking.room.price # admin
class: center, middle
class: center, middle
A class should have only one reason to change
# reason: persistence
class Entity < AR:B
has_many :users
# [...]
end
# reason: collect data about entities by day
class EntityMetadata
scope :between # [...]
end
# extract data about entities
class EntityMiner
# [...]
def touchable_user_average
create_missing_metadata
EntityMetadata.between(period).average(:touchable_user)
end
end
The names you give to your classes will affect the amount of responsibility.
class UserCreator
# [...]
end
class UserManager
# [...]
end
Mr. Miner can you please...
create_missing_metadata
?
- Re-usable
- Clear
- Modular
- Avoid interdependencies
- Keep the logic in one place (eg: file storage)
- Goes along with REST/hypermedia
- What about rails concerns?
class: center, middle
class: center, middle
- Group logic
- Set boundaries
- Reuse code
- Easily find the parts (one) you need to modify / reuse
- Abstract complex concepts
- Best man (class) for the job
Lots of classes and methods
- Namespaces
- Extract services
- Extract gems
- Extract engines
- Kiss
- Profit!
- Not just standups
- Write code happy to accept change
- Readable code (XP)
- It's not a quick s**t in the hood
- Technical debt must be manageable
- Red-green-refactor
- Design Patterns
- Hexagonal feat Rails on a budget
- Naming things
- Test foobar
class: center, middle
Slides available at ???????
Slideshow created using remark (thanks)