Programming Practices – Is Reading from STDIN in a Library an Anti-Pattern?

anti-patternslibrariesprogramming practices

While writing a library for a large project I'm working on at work, an issue came up which required a token to be sent to an email address, and then passed back into the code where it can then be used for further use.

My colleague says to just read from STDIN (using Python: code = input("Enter code: ")) and then have a user pass it in, however to me this seems like bad practice as the library might (in this case definitely will) be used in a background task on a server.

I was wondering whether or not this was considered an anti-pattern or not.

Best Answer

As a general guideline, libraries should be totally disconnected from the environment. That means that they shouldn't perform operations on standard streams, on specific files, or have any expectation about the environment or the context they are used.

Of course, there are exceptions to this rule, but there must be a very good reason for it. In the case of using stdin, i can't find any reason (unless your library actually provides routines for reading from stdin, like std::cin from C++). Also, taking the I/O streams from a parameter rather than having them hardcoded adds so much flexibility that it's not worth not doing it.