How to properly decouple the service layer from the user interface layer, if the service layer needs to interact with the user?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/381084

  •  15-02-2021
  •  | 
  •  

Pergunta

In my program, I have a long-running function from which I would like to interact with the user for various reasons:

  1. Giving status updates ("Downloading file /foo/bar.png")
  2. Displaying warnings ("File upload failed; will retry later")
  3. Asking for input ("Please enter your google drive password")

The problem is, of course, that this function doesn't know how it should interact with the user. For example, it would be nonsensical to display messages on stdout in a GUI program.

In case of errors, the solution is obvious - just throw an exception that'll be caught in the user interface layer. Errors are easy because the service layer's job is done as soon as the exception is thrown. But what about things like warnings and input? How do I bridge the gap between the service layer and the user?

Foi útil?

Solução

Well, what I usually do in situations like this (and my answer isn't specific to Python in this case), is to provide some mechanism within the user-interface layer that allows the user-client code to define "callbacks." The service-layer calls out to the user-interface layer at strategic intervals. This gives the UI layer the chance to invoke a callback should the user have defined one. (If he did not, the call is simply a no-op.)

The "separation of concerns" thus remains clear: the service-layer will call the UI-layer regardless, not knowing (or caring) whether the UI-layer has anything that it should call, and having no idea what such a call would be.

In the Python language, the "callbacks" would of course be closures.

Licenciado em: CC-BY-SA com atribuição
scroll top