8

I have worked with examples like a Player object which knows how to change its own state.

Another example, is an Invoice object which knew how to calculate its invoice charges using an algorithm.

Does this violate the single responsibility principle ?

If yes, then is creating an InvoiceCalculator be the right approach to house the algorithm ?

And the PlayerStateChanger is that a valid thing.

Martin Schröder
  • 354
  • 1
  • 4
  • 19
  • 5
  • 3
    If class changing it's internal state would violate SRP. Then whole idea behind object-orientation is violation of SRP. – Euphoric Oct 23 '19 at 09:32
  • ^What Euphoric said, and 2) there can be valid reasons to choose to structure your program or parts of it in a way that's different from the usual OOP approach; you can have data structures with no behavior, functions working with immutable data, etc. - and then apply SRP to individual functions or to composite units of code (a group of functions + the data they work on). It's about observing how different aspects of the code are coupled, and then deciding if decoupling them is a good idea based the responsibilities they serve.
  • – Filip Milovanović Oct 23 '19 at 09:59
  • Another example is an Invoice object which knew how to calculate its invoice charges using an algorithm. I think this is a bad example because charges are usually calculated in different ways due to different reasons (it varies from country to country and from time to time). The way to calculate them changes oftener than the "data structure" that represents the concept Invoice. For this reason, we use to decouple algorithms from the model they operate with. – Laiv Oct 28 '19 at 15:41