Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should functions always return the same type?

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?

like image 837
self.self Avatar asked Dec 03 '09 11:12

self.self


People also ask

Can a function return 2 different types?

Because the function returns only 2 possible types, TypeScript knows that the type of the value is a number in the else block.

Can a function return different types?

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.

What are the purposes of having return type of the function?

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.

Can Python function have different return types?

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.


1 Answers

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.

like image 123
S.Lott Avatar answered Oct 05 '22 23:10

S.Lott