4 ms·
> you would have found that solution I don't think so, even after seeing your pseudo code don't see a nice way to avoid the early return. I don't understand ho
by Buttons840 7y ago
> you would have found that solution
I don't think so, even after seeing your pseudo code don't see a nice way to avoid the early return. I don't understand how your for-loop / if-condition mix works, but let me try to translate it as best I can into valid Python:
def contains_3(xs):
found = False
index = 0
if not found:
found = xs[index] == 3
index += 1
return found
This was honestly my first best effort attempt at creating this function without an early return. But it is wrong, it only checks if the first value of the list is 3. My opinion is that this style is more error prone (and indeed, I did create an error), and objectively there is more code and more state and thus more opportunities to get things wrong.
def contains_3(xs):
found = False
index = 0
while not found:
found = xs[index] == 3
index += 1
return found
That works, but again, there is more code and more state. When reading this code I must ask myself "are they iterating over the list correctly?" and I must spend mental effort answering that question. This doesn't happen with a for-loop.
I don't understand why you keep talking about jumps in assembly code. Code which has zero early returns will still have hundreds of jumps in the assembly code.
Code that is short is good. Code that is readable is good. I don't think we'll agree on what code is more readable, but we can at least agree on which code is shorter.
As I've gained programming experience I care less and less about how individual functions are implemented and more and more about what those functions do and what they return. For something like `contains_3`, I see that it is a function with no side-effects, which returns a boolean, and wont fail (at least, wont fail in a language with type checking). This is a small simple function, and I don't care how it's implemented, it is a good function. If it becomes a problem for some reason, it is isolated and can be easily fixed in isolation.
- deleted 7y ago[deleted]
- deleted 7y ago[deleted]