Suppose there is a class that writes its state to the disk, and loads it back during initialization. It is logical to do this in the constructor. But in terms of unit tests, this is crooked. If I put it into the initialize method, then I oblige the external code to pull it too, then it produces different statuses initializing and so on.

Do I understand correctly that a good design will be the following:

  • some kind of factory that is responsible for creating and initializing a class
  • LastStateInfo object
  • an additional constructor is added to the class that accepts LastStateInfo

Are there any typical approaches? How it's called? How can you google it?

  • four
    One approach is the keeper pattern (Memento). - Alexander Petrov
  • @AlexanderPetrov would issue a response with minimal code example. - andreycha
  • "How can you google it?" - 1) buy or download GoF, 2) read, 3) if you have questions, refer to the list of templates in the book and quickly find the right one. - andreycha

1 answer 1

To save the state there is a pattern Keeper (Momento). The class itself should not implement the state save / restore algorithm (the reverse violates the SOLID principles, namely SRP). Then there will be no problems with unit tests. Instead of dependencies, slip mocks / stubs.