Object-oriented design
Topics: Object-oriented programming
Object-oriented design models responsibilities and collaborations through object interfaces and behaviour.
Subtopics
Interface
“The public interface is a contract that articulates the responsibilities of your class.” (Sandi Metz, Practical Object-Oriented Design in Ruby - Sandi Metz)
Model behaviour, not state
When modelling objects, our initial instinct is often to model state. A first draft for modelling a police officer might look like this:
- wears a uniform
- carries a gun
- arrests people
- enforces the law
Now, how might a model for an actor playing a police officer look like?
- wears a uniform
- carries a gun
- acts out arresting someone
This approach to modelling leads to a design like this:
classDiagram
Real <|-- PoliceOfficer
Actor <|-- PoliceOfficer
class PoliceOfficer{
String name
String uniformColour
String gunModel
canArrest()
}
class Real{
String precinct
}
class Actor{
String playName
String roleName
}
However, if we look at the behaviours and relationships of these two classes, we’ll realize that they’re completely different. A police officer has several duties, is assigned to a precinct and so on. An actor acts according to a script, has different roles at different times etc.
The following model reflects this better:
classDiagram
PoliceOfficer <|-- Profession
Actor <|-- Profession
Agent <|-- Profession
StageActor <|-- Actor
TVActor <|-- Actor
class Person{
Profession profession
}
class Profession{
String industry
}
class PoliceOfficer{
String uniformColour
String gunModel
arrest()
}
class Actor{
Person agent
Roles[] roles
sign()
}
class Agent{
Actor[] actors
sign()
}
Bookmarks
- Elizabeth Gibson, “Objects — Born and Bred”, BYTE Magazine October 1990