How to tell different classes to save to the same folder during execution of a program?

StackOverflow https://stackoverflow.com/questions/21258480

  •  30-09-2022
  •  | 
  •  

Pergunta

I have a program where the typical use-case is to create a session and during this session, to perform some sequential numeric calculations, where the result of each calculation is passed as parameter to the subsequent one.

It is a requirement that each intermediate numeric result MUST be saved to disk, so that the following situation is achieved:

  1. At the beginning of the session, a new, uniquely-named folder is created;
  2. Each calculation is sequentially run, each by a different classe, and at the end of each calculation, some file with intermediate result is saved in that folder;
  3. At the end of the session (and after the program is closed), the folder could be optionally accessed from the filesystem, and all files would be there.

My doubt is:

"how do I tell each class where is the folder it is supposed to save?".

It is ok for us, architecturally, to have IO code in the classes, but the use of a "global" value containing the path, versus passing the path in the constructor to every class, versus another, more sensible, solution, is confusing me.

Foi útil?

Solução

Passing the path to the constructor of each class is what's known as dependency injection, and it's generally considered the preferable way of doing things, at least at a simple level. The ideal solution would be to inject an instance of a file writer interface into each class as that way you can test each class using a mock writer. That is more complex to implement though. Either way, dependency injection is being used.

By using a global value, you couple all parts of your code to that value. Such coupling should be avoided as it leads to brittle code that can easily break when changes are made. The reason being, that in a large system it can be hard to identify all dependencies on a global item and thus understand the consequences of changing it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top