Too many return-statements = bad style?

Pierre-Frédéric Caillaud peufeu at free.fr
Tue Jul 20 09:38:29 CEST 2004


On 14 Jul 2004 07:13:50 -0700, Steve Thompson <steve_thompson at prodigy.net>  
wrote:


> It is a practice that to me is a mark of good software engineering, as
> is never using 'continue' (why does this useless artifact survive from
> language to language?)

Ok, then : let's split a file into records :

def getrecords( stream ):
	result = []
	for line in stream:
		line = line.strip()
		if not line:
			continue		# useful here
		if line = "end of record delimiter"
			yield result	# could have been a return
			result = []
		parse line and add stuff to result

for record in getrecords( open(filename) ):
	do something


	Also, if you want to put your return at the end of the function only,  
will you do the same with yield ? pretty useless...

> and leaving loops only when the loop condition
> is met.  At the end of the day this means my code is easy to read,
> easy to follow, and fairly well factored.


counter-example :

say item is a filename for instance

for item in items:
	if item does not interest us (like test file name and extension and  
existance):
		continue

	if item says we should stop processing:
		break

	open the file 'item', read the header..., check some parameters in it
	if the result is such that item does not interest us:
		continue

	do some other thing with item and get a result (like read some other data  
and check it)
	if the result is such that item does not interest us:
		continue

	... do things with item and append results to a list for instance

Would you do it that way ?

for item in items:
	if item interest us:
		if item says we should stop processing:
			break # I left this one, would be too ugly to remove
		open the file 'item', read the header..., check some parameters in it
		if the result is such that item does interest us:
			do some other thing with item and get a result
			if the result is such that item still interest us:
				... do things with item and append results to a list for instance


I think the first example is much clearer. Each step can be separated by  
blank lines and a comment line. Indentation is low. continue is explicit  
(whereas with the 'nested ifs' you have to scroll down the editor window  
to check wether there's an else or not)...

	I think this debate is pointless...



>
> And for those folks that actually view many exits as a Good Thing, I
> would argue that increasing the cyclomatic complexity of any piece of
> code is by definition the very antithesis of good software
> engineering.
>
> Best regards to all,
>
>
> Steve




More information about the Python-list mailing list