An example of SRP would be File, FileReader and FileWriter: there are many different ways to read from a file, and many different ways to write to a file. Therefore, these behaviors are composed by their own types (FileReader for reading, FileWriter for writing), allowing you to scale up (add new overloads) while still keeping modular:
File file = new File(...); //Main Type
FileReader reader = new FileReader(file); //Behavior Type
FileWriter writer = new FileWriter(file); //Behavior Type
So how would we determine when a type should be created to take care of a responsibility, such as reading/writing? Even if a behavior doesn't have any overloads, we can't be sure that'll stay true in time.
For example, a GameEngine that can start() and stop(). Since each behavior had no overloads, it would be an overkill to create new types for each behavior. They could both be handled by the GameEngine, and the engine's responsibility would be "managing execution state of the program":
class GameEngine {
public void start() { .. }
public void stop() { .. }
}
If I needed to create overloads, GameEngine would start violating SRP:
class GameEngine {
public void start() { .. }
public void start(Callback startHook) { .. }
public void stop() { .. }
public void stop(Callback endHook) { .. }
}
Modifying this class to abide by SRP would result in breaking code. Does this mean we should create a new type for each kind of behavior, to avoid breaking code? Wouldn't this clutter the namespace?
Aucun commentaire:
Enregistrer un commentaire