Chapter 2: Designing Classes with a Single Responsibility Flashcards
Learn the concepts in chapter 2 of the Practicing Object-Oriented Design book
What is considered as a TRUE code?
A code that is:
- Transparent
- Reasonable
- Usable
- Exemplary
What does a TRUE code measure?
That a code written now will be easily changed in the future
What does a Transparent code mean?
The consequences of change should be obvious in the code that is changing now and in distant code that relies on it
What does a Reasonable code mean?
The cost of any change should be proportional to the benefits the change archives
What does a Usable code mean?
Existing code should be usable in new and unexpected contexts
What does an Exemplary code mean?
The code itself should encourage those who change it to perpetuate the qualities it has
What is the first step in creating code that is TRUE?
It is to ensure that each class has a single, well-defined responsibility
How do you determine if a class has Single Responsibility?
- You can ask questions using the method names
- You can create sentences with the methods names and check if you need conjunctions like ‘and’ or ‘or’ to build the sentence, if so, maybe the method are doing too much.
What is Cohesion?
When everything in a class is related to its central purpose.
What are the techniques to create code that embraces changes?
Depend on behavior, not data
- Hide instance variables
- Hide data structures
Enforce Single Responsibility everywhere
- Extract extra responsibilities from methods
- Isolate Extra Responsabilities in classes
How does the “Hide instance variables” technique work?
Always wrap instance variables in accessor methods instead of directly referring to them.
How does the “Hide data structures” technique work?
You need to separate structure from meaning. For this, we can use the Ruby Struct class to wrap a strucuture
What are the benefits of use methods that have single responsability?
- Expose previously hidden qualities
- Avoid the need for comments
- Encourage reuse
- Are easy to move to another class