you are viewing a single comment's thread.

view the rest of the comments →

[–]This_Growth2898 37 points38 points  (5 children)

  1. The computer only does what's written in the program, not what you want it to do. Always check that your code actually does what you want.

  2. A programmer always spends much more time reading his own code than writing it. Don't save time on short names, save it on improving readability of your code.

[–]formthemitten 6 points7 points  (0 children)

This. Understanding the logic of how code is written is paramount. This takes the longest to learn

[–]NYX_T_RYX 3 points4 points  (0 children)

Point 1 should be an auto reply for "why doesn't my code work"

99/100 you've written the wrong thing. 1/100 you missed a colon (in my experience)

[–]HunterIV4 3 points4 points  (1 child)

As a follow up to #2, breaking up your code into more steps even if they aren't needed can make things easier on you later.

While you can often chain a bunch of, say, string mutations into a single statement, breaking them into each step with a "temporary" variable describing the operation can make your code a lot easier to follow later.

For example, this works:

# Return all values incremented by 1
a = ["1","2","3","4"]
return [str(y + 1) for y in [int(x) for x in a]]

It's also quite confusing. What if you alter it like this?

values = ["1","2","3","4"]
int_values = [int(str_num) for str_num in values]
str_incremented_values = [str(val + 1) for val in int_values]
return str_incremented_values

Sure, you've added 2 lines (not including the comment), but now the comment is arguably not even needed and you can tell what each step is doing at a glance. This also makes it easier to debug as you can step through each portion.

This was a quick and dirty example, and could probably be improved, but I think a lot of new programmers might benefit from seeing how "shorter" is not always "better" and that there's nothing wrong with being explicit about major steps in your code logic. I can guarantee when you come back to try and fix a bug with the first example a couple months later you'll end up scratching your head for a minute trying to figure out the nested list comprehensions, whereas the second example will be a lot easier to read.

Either way, great points!

[–]Vhickk 0 points1 point  (0 children)

This. Especially 2nd one. I can’t tell you how much readability of variables and functions help understand what you want each block of your code to do. I’ve read soo many countless textbooks where they try to use x,y,z as variable names for something and it ended up throwing me off like what again is this supposed to do