Question

Imagine you have a chain of functions calls, in which each function is taking the previous function's output as input for the next calculation in the chain.

Make an assumption that you are leading the infra scope, which means you are defining the process chain and protocol, but you have a group of users that are responsible to implement each cube of the chain (I.e implementation of functions A,B,C and so forth).

Assume we have already a given flow likeA->B->C->D, now imagine that function A sometimes need to return a dictionary and sometimes pandas dataframe as input, this is requirement came from the users, and I think quite break common programming paradigms.

In my opinion, this can have serious inconsistency issues, errors and less testable code.

I would like to hear your thoughts regarding this as a concept
Do you think it is reasonable to return different value type from function according to configuration and having protocol in which each cubes in chain may not talking always on the same protocol? (Discliamer: We are using python)

I tend to see this equivalent to the ability, for example, to populate function parameter function with different types for the same parameter let say (I.e sometimes int sometimes dict) at different function calls - which is wrong.

Although a dynamic type language might let you do it, it's doesn't necessarily mean you should do it, and it may be considered as a bad practice or even abuse of the ability.

Even in python the use of dynamic parameters passing (*args, **kwargs) should be used wisely and in a limited way and only when needed for example here

Was it helpful?

Solution

This is overall a bad practice. Functional language or not, function as a concept should have a given, proper set of inputs (or a single one) and the same for the output, stemming from a mathematical definition of a function. Functional languages bridge this issue of inconsistent return types in chains through the use of monads, which neatly wrap the resulting type in a "container", allowing for easier handling in such calls.

Specific to this case, why wouldn't all of your functions talk on the same protocol? Having a configuration flag indicating which protocol to switch to for all functions doesn't seem like a bad idea, but if some functions are "deaf" in regards to listening to what the configuration says, then you're in for a wild ride of error handling and matching input types. I'd certainly avoid that if possible and I'd always return the same type, avoiding that conf-based function definition as well, for example in your case, I'd always return a dict with the Int value inside it under some specific key.

There's a reason for Python having a practice of docblock-ing functions stating the return type of that function. I'd reformat the code to follow established practices, most likely it'll save you some effort in the long run.

Licensed under: CC-BY-SA with attribution
scroll top