Sorry about the confusing title.
I recently started doing this in my project, and am wondering if it’s more efficient, or not, and if it’s a terrible style to practice.
Here’s an example from a Database interface:
def register(self, user, pw):
"""Register user/pw into the database"""
if self.isStarted():
raise Exceptions.Started
hashed = hashlib.sha512(pw).hexdigest()
self._db_cur.execute('''INSERT INTO PLAYERS (name, password)
values (?, ?)''', [user, hashed])
self._db.commit()
I do it here with raising an exception, but I’ve done it in other places with a return.
I feel this allows the false-cases to exit the function at the top, instead of continuing down the function, seeing if there is any more code for them to run.
I rarely see this in code I look at: is this a bad practice, or does it not yield any performance like I imagine it to?
To help clarify, what I’m used to is:
if (somethingTrue):
runThis()
thisToo()
x = andThis()
return x
return None
and what I’ve started to do, and am iffy on:
if (!somethingTrue):
return None
runThis()
thisToo()
x = andThis()
return x
The latter seems to give the impression (especially in functions longer than 4 lines) that the code isn’t part of a conditional, when it’s intended that way. This also makes it look nicer, while adhering to PEP-8, so I’m really in a toss-up about it.
I have a feeling this breaks something horribly sacred. Is this alright, or sacrilegious?
One part of the question is about style and best practice – therefore IMHO is no ‘correct’ way.
In my opinion the nested version (no direct return) comes from ‘historic’ programming languages like ‘C’ where the whole cleanup is done once at the right place. Artificial example to show the point only:
Here it is not correct to return from other lines than the last one – because then there might be a resource leak.
When using only objects which are destroyed completely in their destructor – or when there is no need to clean up resources (because none were allocated), I prefer the ‘short’ path return. This make things clearer like: if the preconditions for a function is not meet, there is no way to ‘really’ execute the function body. Also: you don’t need that much indentation and it is easier to read.
Performance: I made some tests; I was not able to measure a difference between the two ways. IMHO if you need to tune performance at this level, you might want to think about choosing another programming language. 😉