262 points · by nharada · 11y ago · 160 comments
Whenever I try to think "How would someone smarter than me solve this?", Raymond is one of the people I am thinking about. I'd highly recommend this talk.
Aside: A few days after seeing this, a co-worker asked for my recommendations on a Python project he was working on. Which involved some Python code that was translated over from Java. Pretty much exactly what Raymond was talking about fixing here. I told my coworker he should watch it. A week later he comes to me following up on it, I ask if he's watched it. No... Then he proceeds to ask me what sort of indentation style he should use and what format for the inline docs.
Some takeaways; 1. Adhere to a great style guide 2. Can you predict what the code does? Can you trace a path through the function calls, if statements and for loops? 3. Can you explain to someone what the code -means-? Why is it the way it is?
p = (170, .1, .6);
if p[1] > .5:
print("bright!")
elif p[2] > .5:
print("light")
That's ok, right? Pretty nice. I can see that it'll print "light".Good enough? No, not really. How are "bright" and "light" related to (170, .1, .6) and .5?
How about this?
color = Color(hue=170, saturation=.1, luminosity=.6)
if color.saturation > .5:
print("bright!")
elif color.luminosity > .5:
print("light!")
Far better! I know now that saturation is related to brightness, and that luminosity is related to lightness.
It takes about the same time to write, yet is far more legible.Those things are better explained in a comment, I'd think.
Comments are needed, but should not explain what the code does (as in "add 1 to n") and instead exaplin why it does it (as in "fn expects indices to start from 1").
It can and the code in question will print both "bright" and "light" if passed a color that matches that.
Where did you see that it's an either-or affair in the example?
Besides, the key point, is that the code talks about luminocity and brightness levels, and the second example makes that explicit. No comments needed if you know what HSV is. And if you don't, comments are usually not the place to learn about it.
if color.saturation > .5:
print("bright!")
elif color.luminosity > .5:
print("light!")
it's an `elif`... it will never print both "bright" and "light"This kind of mistake really detracts from the point that was argued here about code being "intelligible"
$ python
>>> if True:
... print "First"
... elif True:
... print "Second"
...
First
>>> def qualify(color):
hue, saturation, luminosity = color
if hue ... or saturation:
...
...For some reason youtube didn't let me change the speed of this video. Instead I downloaded it with youtube-dl and watched it with vlc.
As an example, check out the 7th example in http://research.microsoft.com/en-us/um/people/smcdirm/apx/in....
A humbling reminder of how far I have to go to be even near this guy's level.
runWithNetworkElement("171.0.2.45", networkElement -> {
for (Route route : networkElement.routingTable()) {
System.out.printf("%15s -> %s%n", route.name(), route.ipaddr());
}
});Sure, Java 8 has lambads, but have their disposed of getters and setters and added some kind of properties?
If not, then the idiomatic way is not name(), it's getName().
(Of course without "unified property access", it's not that much different)
For example, both Google's AutoValue library and the Immutables library show examples of getters that drop the "get" prefix:
https://github.com/google/auto/tree/master/value
One argument against the prefix is that immutable value types don't have setters, so it's not as important to distinguish between them. Another argument is that immutable values aren't really objects in the object-oriented sense, so accessing a field really is just a data access as oppose to an action being performed by the class instance.
(I guess one aspect of Java that makes this less awkward to implement is that methods and fields have independent namespaces, so nothing stops the Route class from having both a "name" field and a "name()" method. That's possible because Java doesn't have first-class functions, so you can always determine from usage whether something is a field or a method.)
That being said, I almost couldn't get past the obnoxious rant at the beginning against maximum line length. The reasons for the rule are made very clear in pep8 as well as the fact that it's not a hard rule and it's fine to override it in your team if you all agree on longer lines.
And are still BS with today's monitors (including laptop monitors).
Besides, PEP8 itself goes on to say: " For code maintained exclusively or primarily by a team that can reach agreement on this issue, it is okay to increase the nominal line length from 80 to 100 characters (effectively increasing the maximum length to 99 characters), provided that comments and docstrings are still wrapped at 72 characters."
My 15" laptop monitor can only (readably to me) fit two 100-wide buffers in a visually barebone editor (emacs), move to an editor or IDE where the UI takes more horizontal space because of sidebars (Atom, IntelliJ) and the buffers are close to 80-wide, so 80-wide is a perfectly fine limit as far as I'm concerned.
Until I have to perform a 3-way merge, then 80-wide doesn't fit anymore.
And age will eventually catch up to me and make things worse.
And for those, you can always either wrap or scroll a little to see them in a 3 way merge, it's not a big deal.
Heck, in the eighties that you champion and that they got that rule, they worked with a single 80-wide terminal view, not 2 100-wide side by side and no 3 way merges.
I doubt that I was or am nearly as good an editor as he is a coder. Yet I think that there is a logical progression (not a natural progression, since we don't all make it) from knowing the rules to knowing what the rules are for, to having the confidence to break them when it makes sense.
A few months ago I started to get into some networking and saw that there were a few free online courses available. Unfortunately, despite choosing my favorite one, I ended up falling asleep 3 times already listening to the lectures. Man, I sound like I'm getting old...
And then I realized this is all BS. I wrote a very short styleguide with a linkback to pep8 for any "questions" one might have. Problem solved. You don't need to decide every little detail of how your code is going to look in advance, unless there is a solid reason to do so.
The styleguide, for those curious: https://github.com/jleclanche/fireplace/blob/master/CONTRIBU...
Edit: What a great talk. Really embraces the way I've been thinking about pythonic coding. Loved it.
Sure there are huge monitors with insane dpi allowing a ridiculous amount of text, but I'm not getting younger and find myself increasing font size every now and then to be able to read.
Getting old sucks sometimes.
If you take a blatantly non-compliant codebase and PEP8-ify it, you'll have many "pep8" lines in your git blame for a point, but by integrating it in your process that will disappear pretty clean.
In fact, he proposed the total inverse of what you say.
He said, code standards like PEP8 are good, and should be followed. But those are only code formatting standards.
The beyond part wasn't about doing things "his way instead of the standard way" but about doing things the Python way (idiomatic Python) instead of ad-hoc or mimicking other languages you're familiar with way.
What he showed are common standard Python approaches to solving issues, taking advantage of what Python offers instead of writing in C or Java etc style.
Really, your comment couldn't be further from the spirit and content of the talk.
(Of course this is already obvious since the 80-column thing is about PEP8, whereas the essense of the talk is how to better structure your code BEYOND PEP8's formatting rules).
Not to mention that even PEP8 concedes that you can raise the max line length limit up to 100 if your team agrees.
I know some people program with one editor maximised and can have 200 character lines if they like, but a specific width as a convention is helpful. And the convention that is already widely used is going to make fewer people have to accommodate you. The 'ish' is useless in that regard.
Ayup. That reason is teletypewriters (aka ttys).
The biggest problem I have with most programmers is naming things well. 80 columns is anathema to good naming. People start using mbl instead of maxExchangeBufferLengthBytes.
No, I'm not a Java guy. I spend a LOT of time chewing through embedded C code. I don't even have good autocomplete in most embedded IDE's, and I STILL prefer maxExchangeBufferLengthBytes. Here's why--that name tells me many things at a glance:
max--limit of some form, probably should be positive
ExchangeBuffer--a buffer and it's functional purpose
LengthBytes--a length (so likely unsigned and if I see differently I should pause) in bytes (not items). You would be amazed at the number of bugs this circumvents.
That's a huge amount of information conveyed in 30 bytes. But that's almost half of 80 columns. Add in something like 8 column indents and you can't even name things well.
And, that still probably doesn't give me enough information. I need to look at that to see if that is constant, and I probably need to see if I can touch that without concurrency considerations.
I read code far more often than I type it. I read code after I have forgotten about it far more often than when it is fresh.
Naming things to enable me to come back to my code 6 years later, refresh my memory, and not screw up while doing it is the single most important task in my programming.
80 columns is simply not conducive to that.
That's why pilots are recommended to scan horizontally no more than about 10 degrees at a time when looking out for other aircraft: http://www.skybrary.aero/index.php/Visual_Scanning_Technique
Having lines be too short is also a concern for legibility, because even when lines are short, there's always the risk of the reader missing the next line at every line break.
The 80 character line is actually an artifact of punch cards, which supported 80 characters per card. And that's probably a remnant of some automatic loom that for some design reason, worked best with instructions fed in chunks of 80s.
Except that you are wrong.
One of the links in the comments here has research that shows that reading speed increases significantly to at least 90 characters and may increase further than that.
It's a bit handwavey otherwise. I'm also a long-names fan, sometimes I go overboard, but in 20 years I've not been able to logically break my line in an obvious place only once or twice.
class VendorOrderShipmentResource():
...
def post(...):
...
for item in data.order_items:
...
if not shipment_qty:
abort(400, message='All order_items must have a quantity_to_ship.')
That line goes out to col 86. I realize that it's possible to break it like this (#1): abort(
400, message='All order_items must have a quantity_to_ship.')
or this (#2): abort(
400,
message='All order_items must have a quantity_to_ship.'
)
or this (#3): msg = 'All order_items must have a quantity_to_ship.'
abort(400, message=msg)
or this (#4): abort(400, message='All order_items must have a '
'quantity_to_ship')
I'm not really a fan of any of those:1. I'm not a fan of this one, in this case at least, because it "looks weird" due to the mismatch between the length of the function name, and the length of the next line. Also, I'm not a fan of "hiding" the closing parenthesis at the end of the line, rather than putting it on new line at the original indent level (like #2).
2. I'm not really a fan of this because the first argument and the function name are so much shorter than the message argument, that it looks really lopsided.
3. I'm not a fan of this because it seems stupid to create a new variable just to use it on the next line (and never again).
4. I'm not really a fan of breaking strings up this way, but sometimes I'm forced to. Breaking strings up this way tends to be really fragile when you want to modify them, and might need to reflow the entire wrap.
Personally, I'm just a fan of increasing line length to ~100. The number of things that go over 100 columns (in practice) is much smaller than the number of things that go over 80 columns.
class Batman():
# ...
def handle_jokes(self, villains):
for villain in villains:
if villain.supports_jokes:
formats, transports = villain.query_joke_formats_and_transports()
# ...
That long line is 82 characters. Assume there's a good reason formats and transports are queried together. In practice this leads to variable names f and t. :(Sure:
thisIsAnOutgoingBuffer = this_is_a_function(descriptiveKeywordArg = maxExchangeBufferLengthBytes, ...)
It's been a while, but I seem to recall that Python would require a continuation character to break anywhere prior to the comma.
Yeah, that was nice for 80 line terminals in 1986.
This is 2015. We have 27" screens. Two of them for most of us.
And on our lowly laptops, we have hi-dpi fonts (which makes smaller fonts sizes read great) and widescreens.
The number of programmers I see manically toggling through their code in one window is crazy. I think this is part of the legacy of some high-profile IDEs that gave you one window at a time.
What proportion of your code lines are > 80 cols? Multiply that by the amount of extra width to get the wasted screen estate. I'll take that and put more code/docs/tests/output on my screen at the same time and have to toggle less.
The idea that this is about teletype is very amusing, but rather naive.
Even on a widescreen laptop you can have 2 > 100 lines windows side by side. And for multi-monitor setups you can go even wilder.
>The number of programmers I see manically toggling through their code in one window is crazy. I think this is part of the legacy of some high-profile IDEs that gave you one window at a time.
If you have tons of junk in front of you, you're not focusing on your code as you should be.
Plus, with most editors that can jump in / out of functions, it's not like I'm losing my place. In fact, my editors all save my place in files on exit.
if __name__ == '__main__':
def this_is_a_function(*args, **kwargs):
def this_is_a_helper_function(arg1,
arg2=('this line is already indented 39 '
'chars!')):
this_long_variable = ("Don't put an expression here unless you "
"want to use useless intermediate variabls.")
return this_long variable if var else 'really short here'
return 1
And some people want to insist on 8 char indents! def this_is_a_function(*args, **kws):
def this_is_a_helper_function(
arg1,
arg2='this line is indented 12 chars!'):
this_long_variable = (
'Don\'t put an expression here unless you '
'want to use useless intermediate variables')
return this_long_variable if var else 'really short here'
return 1
(for the same number of lines) or better still follow some basic common sense:1. Local functions should be short and have short names since their scope is limited.
2. Local variables, similarly
3. Don't put long explicit strings in code.
and get
messages = dict(
long_default = \
'Don\'t write strings that may wrap in ugly ways on 80 col shells.',
short_default = 'Keep it short'
)
def this_is_a_function(parameter):
def message(long, message='this is only 36 chars'):
long_message = messages.long_default
short_message = message or messages.short_default
return long_message if long else short_message
# Do something here.
return 1
And if you have an expression that is more than 80 characters long, breaking bits of that expression and assigning them to temporary variables is not 'useless', it makes code clearer and is only rarely a performance hit.In other words, I try to use vertical space for higher-level work than horizontal space, and when you have to fit both into vertical space, you lose some clarity in high-level in order to gain it in low-level.
if __name__ == '__main__':
def this_is_a_function(*args, **kwargs):
def this_is_a_helper_function(
arg1,
arg2='this line is now indented 12 chars!'
):
this_long_variable = (
"Don't put an expression here unless you "
"want to use useless intermediate variabls."
)
return this_long variable if var else 'really short here'
return 1 Flat is better than nested.
Too many levels of nesting is definitely a code smell. Often it's better to pull those helper functions out, and/or create function or method factory functions at a higher level of organization.(Go, for some reason, doesn't like splitting lines at all, no matter how wide. I've had code reviewers criticise me splitting lines at 200, which I don't understand at all.)
Recently code-editors have started to learn how. Don't wrap your lines at all; let the editor do that, in realtime, and you can have your windows at whatever width you want.
As far as I can tell, that reason is the IBM 80 column punch card standard launched in 1928:
https://en.wikipedia.org/wiki/Punched_card#IBM_80-column_pun...
You can't standardise based on what you are fond of. That's the point of a standard. When such a large proportion of people, and the standard library, and most shells, use 80, then using 120 will inconvenience them. If you load my 80col code into your 120 col editor, it will not inconvenience you at all, barring an occasional extra line break.
No.
>You can't standardise based on what you are fond of.
Sure you can. That's why company and team-wide standards are for.
Nobody has to be forced to use some BS 70's throwback rules just because they are in PEP8.
When lines are longer it becomes more difficult for your eyes to keep track of where the next line is. Furthermore, code is not formatted as paragraphs but as separate lines, so you end up wasting a lot of screen estate for those few long lines. Having a low maximum means it will be close to the average and a larger proportion of the screen is utilized.
Actually this claim is disputed: http://psychology.wichita.edu/surl/usabilitynews/72/LineLeng...
I like to joke God made The VT52 with 80 columns because that's how terminals should be.
Another I use is that "80 columns should be enough for anyone".
Now, seriously, code that's too wide (or too long) is a code smell. You probably should name your variables better, have fewer them in scope or just refactor the code to be more readable. Remember: code is executed by very cheaply and read by very expensive humans. Optimize for the latter.
You're assuming you have just one window open, aren't you? There's less wasted space with 80 cols if you have multiple columns (of the same file, or different files). The math is elsewhere in this thread.
Settings > Editor > General:
* check "Use soft wraps in editor"
* check "Use original line's indent for wrapped parts"
* enter 4 for "Additional shift"
* if you open huge files with wide lines, check "Show soft wraps for current line only" to prevent slowness
I like standards, but 80 chars just isnt enough and never was. Is 96 the next reasonable number?
I’ve seen 66 characters recommended as a maximum line width as a style guide for typewritten documents. You also want some extra room for extra margins, line numbering, etc. If 66 is taken as a good minimal number, then 64 (2⁶) is too small, so let’s add, say, 16 to 64, giving 80 columns.
Paper documents have the form that they do for a reason. You never saw someone writing sideways on a paper (landscape alignment). This is because readability suffers when lines are too long. Even if boxes resized automatically, it’s the line length that’s the problem, not the resizing or scrolling.
Most lines in code that is well structured and simple are less than 80 cols wide. Lines that require more than that can be broken. I think in 20 years of Python I've only seen a couple of cases where there wasn't an obvious semantic break point, most of the time such breaks are easy to place at logical points.
When you have 80 cols you have more code in your window. You can use the resolution to have taller windows and more windows side-by-side. 1920 pixels gives you nicely 3x80 col editors. Which allows you to look at the code, and its tests, and the shell at the same time, for example.
Depending on your font. I use 1920 (-Misc-Fixed-Medium-R-SemiCondensed--13-120-75-75-C-60-ISO10646-1), and I get almost 4x80 col's, 3x96 works nice.