I read somewhere that functions should always return only one type so the following code is considered as bad code:
def x(foo): if 'bar' in foo: return (foo, 'bar') return None
I guess the better solution would be
def x(foo): if 'bar' in foo: return (foo, 'bar') return ()
Wouldn't it be cheaper memory wise to return a None then to create a new empty tuple or is this time difference too small to notice even in larger projects?
Because the function returns only 2 possible types, TypeScript knows that the type of the value is a number in the else block.
If the return type is always derived from a specific class: You can use templates, if you know what type to return before you call the function. But you can't have a function, which internally decide to return some type.
In computer programming, the return type (or result type) defines and constrains the data type of the value returned from a subroutine or method. In many programming languages (especially statically-typed programming languages such as C, C++, Java) the return type must be explicitly specified when declaring a function.
returns different types, as both python None and Javascript null are types on their own right. All these use cases would have their counterpart in static languages, function would just return a proper interface.
Why should functions return values of a consistent type? To meet the following two rules.
Rule 1 -- a function has a "type" -- inputs mapped to outputs. It must return a consistent type of result, or it isn't a function. It's a mess.
Mathematically, we say some function, F, is a mapping from domain, D, to range, R. F: D -> R
. The domain and range form the "type" of the function. The input types and the result type are as essential to the definition of the function as is the name or the body.
Rule 2 -- when you have a "problem" or can't return a proper result, raise an exception.
def x(foo): if 'bar' in foo: return (foo, 'bar') raise Exception( "oh, dear me." )
You can break the above rules, but the cost of long-term maintainability and comprehensibility is astronomical.
"Wouldn't it be cheaper memory wise to return a None?" Wrong question.
The point is not to optimize memory at the cost of clear, readable, obvious code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With