4

If I need to write a program that

  1. Reads a json file
  2. Converts its data to yaml
  3. Writes it to yaml file

and adhering to the single responsibility principle I create classes like

  1. FileReader
  2. JsonToYamlConverter
  3. FileWriter

everything looks good, but then I need to create some class to invoke all these classes, wouldn't it violate the single responsibility principle?

13

The best way to understand the SRP is to work with the interpretation of "responsibility" as being "something that some external force to the program could cause a need to change". In this case, it's hard to see why your module that combines your three classes could be made to change other than by a complete change of what the program actually does, which I reckon is only a single reason to change.

Now, your JsonToYamlConverter however: that has 2 reasons to change: the input format could be changed from JSON to something else, or the output format could be changed from YAML to something else. Your best bet would be to use a JsonReader to produce an object structure and a YamlWriter to consume it.

1

Yes.

But we can get around it by saying that the Programs responsibility is to ensure that X, Y and Z are executed in the correct order, passing the info from one to the next

It doesn't care how they are achieved, that is the responsibility of the individual classes. It only cares that about the "orchestration" of the tasks.

1

"but then I need to create some class to invoke all these classes, wouldn't it violate the single responsibility principle?"

I think I see what's the cause of your confusion; this is not in itself a violation of the SRP, because newly introduced class is not actually responsible for the behaviors implemented by the other classes.

It simply receives some high level requests and forwards (parts of) the work to those other classes. Its responsibility is to coordinate their interaction in some way.

One of the key motivations behind SRP is to avoid interdependencies between parts of the code that handle each responsibility (if it's all in the same class, the code can become tangled in subtle ways). Having separate, well defined public interfaces1 helps with that, because it hides the implementation details, and limits/structures the ways in which these classes can interact - so that a change request that affects only one of the classes has limited effect (or, ideally, no effect) on the others.

1 I don't necessarily mean C# or Java interface types.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.