71 comments

[ 1.6 ms ] story [ 112 ms ] thread
As for functions, there is an explicit benefit in cutting your longer (pure!) functions into a few shorter ones if possible:

Functions communicate with the outside world only via arguments and returned values. The explicit split reassures the reader that this is indeed the case, and thus every reader doesn't have to establish this fact via careful reasoning again and again.

A long function might indeed be simple, but you never know until you check carefully.

(This only applies to pure functions. Natural language sentences and side effecting procedures are messier.)

On the other hand, function calls in hot code are expensive.
Pareto Principle: don't treat all of your code as if it is "hot." It isn't.
Or the law of opposites: you can't have hot without cold. Then again, you can also judge something as cold when it's hot, for instance a big loop inside a function that gets called once, and you're only profiling at the level of function call counts.
Only if your compiler ain't smart enough.

Yes, for some compilers and interpreters performance considerations will force you to write less than readable code.

Inlining is great but it's generally finnicky and hard to control so when it comes to hot loops that matter you may as well do it by hand.
Most compilers have a way to explicitly force functions to be inlined. "Just inline it by hand" is terrible advice.
I'd be very interested to see a compiler where you can force inlining. How does it handle cycles in the call graph? How does it handle code bloat because the inline keyword was used too often?

In GCC at least, you can only give suggestions. The following options control the inliner:

--

max-inline-insns-single: Several parameters control the tree inliner used in gcc. This number sets the maximum number of instructions (counted in gcc's internal representation) in a single function that the tree inliner will consider for inlining. This only affects functions declared inline and methods implemented in a class declaration (C++). The default value is 300.

max-inline-insns-auto: When you use -finline-functions (included in -O3), a lot of functions that would otherwise not be considered for inlining by the compiler will be investigated. To those functions, a different (more restrictive) limit compared to functions declared inline can be applied. The default value is 300.

max-inline-insns: The tree inliner does decrease the allowable size for single functions to be inlined after we already inlined the number of instructions given here by repeated inlining. This number should be a factor of two or more larger than the single function limit. Higher numbers result in better runtime performance, but incur higher compile-time resource (CPU time, memory) requirements and result in larger binaries. Very high values are not advisable, as too large binaries may adversely affect runtime performance. The default value is 600.

max-inline-slope: After exceeding the maximum number of inlined instructions by repeated inlining, a linear function is used to decrease the allowable size for single functions. The slope of that function is the negative reciprocal of the number specified here. The default value is 32.

min-inline-insns: The repeated inlining is throttled more and more by the linear function after exceeding the limit. To avoid too much throttling, a minimum for this function is specified here to allow repeated inlining for very small functions even when a lot of repeated inlining already has been done. The default value is 130.

max-inline-insns-rtl: For languages that use the RTL inliner (this happens at a later stage than tree inlining), you can set the maximum allowable size (counted in RTL instructions) for the RTL inliner with this parameter. The default value is 600.

--

So, while the inliner is great, if performance really matters for a hot loop, and you definitely want that code to be inlined, you might end up having to do it by hand. Because otherwise, if you change something somewhere else in your program, the inliner might suddenly decide not to inline your function anymore. You could say the same thing about virtual functions: devirtualization is great but it's not guaranteed. Or loop unrolling. Or codegen. Or whatever.

GCC and clang have __attribute__((always_inline)). VC++ has __forceinline. All of these will always inline unless it hits a recursive call. They do not attempt to avoid code bloat from the programmer telling it to do stupid things.
Ok, I forgot about always_inline. That is a good point. Anyway, it doesn't work for polymorphic (technically non-static) or recursive code. If you've split your program up into lots of pretty little functions, which is fine, you probably have a bunch of polymorphic and recursive code. Typically you get rid of those things by inlining and/or cloning. (Recursive algorithms use the call stack as an implicit data structure, which you can get rid of by introducing an explicit stack locally.) So, to force the compiler to inline some stuff, you have to inline some other stuff. Which is also fine, just that compilers are not magic. For really important things, you need to look at the generated output and decide if you can do better.
On the third hand, premature optimisation is the root of all evil. :-) It's a lot easier to convert well chunked, modular functions into monolithic blocks than it is to go the other way around.
There was just recently an article about how there is merit to the idea that it is easier to chunk up a monolith than it is to reason about poorly done microservices. Functions, when used in excess, seem to fit the same pattern. Now... good luck getting me to define excess. :)
The HN discussion of the article (MonolithFirst) was https://news.ycombinator.com/item?id=9652893 , and it's a good point to bring up.

I think that that article describes a reaction against a too-hasty move towards microservices, and (as someone who's not a businessperson myself!) as such it seems well advised; but I suspect that there is, among programmers at large, no too-hasty move towards 'microfunctions', and so no corresponding need to urge people to make the kind of monolithic monstrosities that novice (and even sometimes experienced) programmers are all too willing to make anyway.

I bet the author calls for making functions just right in size to leverage self-containment and complexity, instead of panicking after crossing some magical number of lines.

This is actually compatible with DRY, because overpartitioned functionality will require more state to be pulled from function to function, resulting in repeating, long argument lists.

More basic than that, it also forces you to physically move away from the function in order to continue reading. It would be like turning to a different page in order to read the middle part of a paragraph.
another way to accomplish this goal is to write your function using only const variables. every time you'd mutate a variable, use a new const variable instead. you end up transforming the code into static-single-assignment form, which is what compilers do anyway, so you can be sure it won't degrade performance.

this style really makes you wish C/C++ had if expressions. you end up using a lot of ternary operators to compensate.

it makes the code a bit more verbose, but its worlds better than poring through a function to make sure nothing is mutated in an unexpected way.

I reach for Haskell whenever possible to get similar effects.
I actually prefer ternary expressions in many situations, once you're familiar with the syntax they're more concise and more clearly an expression rather than flow control.
> you end up transforming the code into static-single-assignment form, which is what compilers do anyway, so you can be sure it won't degrade performance.

I don't know my way around compiler internals, but this sounds a little suspect to me. It seems to me—just a tyro's opinion—that (1) work spent doing what the compiler will do anyway is probably work wasted, and (2) it is possible to get in the compiler's way even if you are trying just to do what it would do anyway, thus causing unexpected degradation.

Have you measured this benefit in any empirical way?

It is a bit dated now, but Code Complete cites actual attempts to study the connections between function length and maintenance cost in real world code bases. The conclusion was that functions with a high internal complexity were maintenance hazards. Basically add up all of the if's, loops, and so on, and if that is a big number, then break it up. However long functions without internal complexity were not a maintenance hazard. This was true up to about 200 lines.

OK, a lot has changed since IBM studied maintenance costs in the 1980s. But the received wisdom today about short functions was already the received wisdom then. And the wisdom today is just as much based on opinion as it was then.

Is there any more reason why we should accept the received wisdom today than there was then?

Good points.

My argument was actually mostly from a Haskell point of view, and a study there would be somewhat harder to define: you are defining functions all the time: especially in imperative code (do-block / monads) each line is actually a callback.

You could go by purely syntactical criteria, though. Culturally, even a single screenful of code is considered rather long for one definition in Haskell.

A comma splice is a comma splice, and subbing in a colon doesn't change that. A semi-colon, the bastard offspring of the two, does... curious.
His paragraphs are way too long for my tastes.
Disclaimer: I'm not a native English speaker.

Sorry but IMO the author has failed to prove his case. The text is not easy to read, and it's hard to follow the author's thought.

So long sentences and long paragraphs definitely don't help. It's either that or I should get tested for ADHD.

(comment deleted)
I think that's the what the author missed.

Short sentences are not about simplicity, they are about accessibility. While it was not hard for me to read his text. It did not flow, and was not easy to follow. Long sentences distract the reader with their additional complexity. Instead of being able to focus on the content, the reader must decipher the meaning. Then they can engage the idea.

Making it harder to understand content is a terrible way to communicate.

The author seems to be deliberately trying to manufacture long sentences to make his point, mainly by taking two related sentences and pushing them together with a semicolon. It serves no purpose in improving comprehension and comes at the cost of making parsing more difficult. It feels rather like the sort of hypercorrection [1] that people sometimes make when they're trying to sound erudite.

1. https://en.wikipedia.org/wiki/Hypercorrection

Another thing people do when they're trying to sound erudite is ostentatiously [1] link definitions to concepts they think their readers can't look up for themselves.

1. Don't do that

Just because I can look it up for myself doesn't mean I don't appreciate having a link, especially if the writer went to the effort of choosing a link that's better than the first Google search result.

1. Since apparently we’re overthinking things, have you considered that your oversensitivity to minor perceived offenses is because you’ve never been punched?

My thought exactly: "Someone's found the semicolon key"

Most of those semicolons could be replaced with a full stop or comma without losing any meaning.

John Donne, bad writer?

"If a clod be washed away by the sea, Europe is the less, as well as if a promontory were, as well as if a manor of thy friend's or of thine own were: any man's death diminishes me, because I am involved in mankind, and therefore never send to know for whom the bell tolls; it tolls for thee."

A 17th century writer. More importantly, a poet.

Not sure how I feel about the point of the article, but this sheds no light on it - Donne's work is pretty different from modern prose. Different best practices apply.

Actually, it does serve a purpose: it allows you to accurately mark a syntactic hierarchy, indicating clause separation, as distinct from phrase separation. This is especially important when you have two complementary clauses whose relationship should be highlighted, as in the author's

"So if you find yourself breaking sentences apart to follow a rule that sentences should be short, you’re doing it wrong; if they can be broken apart without much trouble, they also weren’t any trouble for the reader to understand in the first place."

Sure, he could make them two separate sentences—but why waste the opportunity to signal their relatedness? Separating the two with a period represents them as equally related to other surrounding sentences. We can decode their connection still, but signaling it explicitly just makes it smoother.

I found his writing to be extremely clear, easy to follow, and enjoyable to read.

Here's the thing: two sentences right next to each other within the same paragraph are related. The sentence is merely one tier in the hierarchy of organizational structures that frame writing. The paragraph also forms a unit of structure in which one or more related sentences collectively convey an idea.

I'm not suggesting there is no use for a semicolon - for example, I like to use it as a separator for a list of clauses if one or more of the clauses contain commas - and of course this is one of those grey areas of English grammar in which the author's use is not objectively wrong. However, it overloads the sentence and makes reading more difficult without any real benefit over the simpler alternative of connecting related sentences in paragraphs.

Likewise, I'm not opposed to writing long sentences. After all, the first sentence in the previous paragraph runs 56 words. However, I am opposed to writing long sentences merely for the sake of claiming that long sentences are okay.

It's been quite some time since I was in school, but it seems the author breaks grammatical rules regarding the number of phrases and clauses that can be strung together with punctuation. In addition, he uses a semicolon where a dash was necessary.

It's dangerous to publicly give a lesson as we sometimes stumble during our lecture (as I probably have done in my comments on the author's essay :) ).

As others have already pointed out, the author does not seem to command long sentences enough. But it can be a good choice for streams-of-consciousness; Marcel Proust is a good example of it. Here are his five longest sentences:

https://nathanbrixius.wordpress.com/2013/10/30/the-five-long...

In general, I'd recommend to read some Proust as his style is completely against the current trend of short, direct sentences à la Hemingway, and that can be refreshing!

By the way, I started reading Proust because of Nabokov's Lectures on Literature:

http://www.amazon.com/Lectures-Literature-Vladimir-Nabokov/d...

Which I recommend wholeheartedly.

As art this ^ sort of thing can be excused.

I would certainly hope that in most business or communication contexts, people aren't going to think a Proustian stream-of-consciousness rat nest is an acceptable piece of writing.

Much of my job is scientific writing. I don't see long sentences as something that is automatically bad. I do see them as a kind of "writing smell" (much like a "code smell") that can indicate something hard to understand. And often the long sentences could be bisected with an increase of understanding.

When possible I write with a text editor and LaTeX, with one sentence per line. This makes it really easy to identify sentences that might possibly be too long.

One sentence per line is also an excellent strategy for when it comes time to "diff" two files. It helps diff identify edits (by giving it more anchoring lines to figure out what's actually changed), and it makes the output much easier to read.
“This sentence has five words. Here are five more words. Five-word sentences are fine. But several together become monotonous. Listen to what is happening. The writing is getting boring. The sound of it drones. It’s like a stuck record. The ear demands some variety. Now listen. I vary the sentence length, and I create music. Music. The writing sings. It has a pleasant rhythm, a lilt, a harmony. I use short sentences. And I use sentences of medium length. And sometimes, when I am certain the reader is rested, I will engage him with a sentence of considerable length, a sentence that burns with energy and builds with all the impetus of a crescendo, the roll of the drums, the crash of the cymbals–sounds that say listen to this, it is important.” - Gary Provost
Like a lot of things, I think it depends mostly on the effort the writer puts into mastering his craft. I prefer the variety in length, and agree with it as a general rule. However, one counterpoint: Hemmingway seems to have done fine with (mostly) short sentences.
The last sentence is still too long though ;)
You're just compromising. Removing complication does make it easier to understand. Short and simple is even easier.

However, it's hard to write that way, so most don't bother. If we rewrote your essay with a mixture of short and long sentences it would be stronger.

Shorter sentences can also seem less thoughtful—even childlike. That doesn't mean they are.

Is there any science available about pure physical aspect of long sentence? I mean... more words to read might equal to more resources spent ... like ATP or neurotransmiters
I write a lot of stuff, trying to churn out one post per week or so, sometimes more, sometimes less (at http://cyclebath.org.uk/).

If you are writing for a broad audience I try not to get too complicated. These days, I usually take the final post, and just throw it up onto http://www.hemingwayapp.com/ to get a feel for how well it reads.

As an experiment I tried to get a "Very Good". Each sentence was clean, had one idea in it, but the flow of the post was stilted. It removed all passion.

However I can be too clever for my own good. Communicating ideas in the simplest terms is exceptionally important. I get too involved in story telling. The Hemmingway App enables a good compromise.

“I have only made this letter longer because I have not had the time to make it shorter." - Blaise Pascal
ObPierreBourdieu:

> This structure which is present in every artistic genre, and has been for a long time, today tends to work as a mental structure, organizing the production and perception of products: the opposition between art and money (the "commercial") is the generating principle of most of the judgments which, in matters of theatre, cinema, painting, literature, claim to establish the frontier between what is art and what is not, between "bourgeois" art and "intellectual" art, between "traditional" art and "avant-garde" art.

(from Pierre Bourdieu, Les règles de l'art, free translation)

I found that hard to follow -- was that your intent? (What does 'this structure' refer to? What does it have to do with 'the opposition'? Are they the same?)
I didn't write it, Pierre Bourdieu did (in French, but my translation follows the sentence fairly closely), and he has stated that he writes like that so that he's hard to quote. In fact, to really understand the sentence, you'd need to read the one before it, and probably the one before that, and they're all about as complicated and hard to understand; you find yourself having to turn to the previous page just to remember what the subject of the sentence was.
For me, it's not whether the sentence is too complicated or too long, but the tools you use within it to make it stick (not the best word but I can't think of a better one at the moment) in the readers or listeners mind.

One of my favorite classes in uni was rhetoric, and one of my favorite books to this day is Farnsworth's Classical English Rhetoric. I highly suggest it as a tote around, open to a random page and read as much as you like and never be disappointed reading.

http://www.amazon.com/Farnsworths-Classical-English-Rhetoric...

I've always learned the edict to simplify writing from as: when writing, try and keep it to simple, single compound, or single complex sentences. Rather than "don't do ___", it's "freely express yourself with ____".

Outside anything else, it's a more pleasant way to approach the topic, and there's a ton of freedom in it. Yes, it's similar to prescribing a word count or a page count because it puts a more-easily measured test on the writing. But it's also an indicating function to help stop a writer from introducing confusion through their grammar.

Some industries have done quite a bit of research into the subject. Take, for example, the aerospace industry's Simplified Technical English[1][2]. Here, research into the readability of flight and maintenance manuals identified that shorter sentences were easier to understand for English-as-a-Second-Language speakers. A grammar was developed to reduce some of English's flexibility and make construction more predictable. This, paired with shorter sentences, dramatically increased the usability of print media for aerospace and defense applications.

Shorter or simpler sentence construction can ultimately free the writer to be more expressive and to more clearly express his or her ideas.

1: http://www.plainlanguagenetwork.org/conferences/2002/aecma/a...

2: http://www.asd-ste100.org/

I've always learned the edict to simplify writing from as:...

I'm terribly sorry, but after scanning that several times, my parser grew weary and I found that I did not have the courage to go on.

YArchive is one of my favorite "tons of useful discussions" sites for when I want to enjoy what the Internet used to be like in usenet's heyday.
> And the pieces do have to be simpler, for the effort to make sense; otherwise the reader of the code is left contemplating not just a horrible mess, but a horrible mess that has metastasized.

This is called "Bulldozer Code"

Congratulations for reading the article and exacting content.

I think the meta observation is there are rules imposed on students to prevent them from developing bad habits. But these aren't hard rules in practice. Same applies to code slopping.

I find your tone unnecessarily arrogant and passive-aggressive.

The point was (which the author made) that simply shortening sentences doesn't necessarily fix a problem with complexity, just like breaking up code without solving the complexity issues also doesn't necessarily fix the problem.

Congratulations for being a supercilious jerk.

The argument would be more compelling from a more compelling writer. The second sentence, "It’s one of the pieces of advice that I have always completely disregarded, as being obviously wrong..." contains a comma that hasn't appealed to the English eye since Jane Austen and is in any case unnecessary. Physician, heal thyself.
The next sentence should lose the comma as well.

"A sentence that is long can still be quite simple, if it doesn’t require the reader to remember previous parts of the sentence in order to parse the rest."

It's almost as if he's using unnecessary commas to make up for the long sentence.

The pause from the comma makes the sentence come off a bit condescending. I felt like I was being talked down to.
Speed reading technique: read 1/3 over on line 1, then 2/3 over on line 1, then 1/3 over on line 2, 2/3 on line 2.. etc. Drastically increases speed, even over the Gary Provost quote.
It is a good rule of thumb in writing not to make the reader work hard to get your meaning, to have to blast for it if you will.

Brevity promotes simplicity and simple things are much easier to understand than are those that are prolix.

So writing in a style consisting primarily of short, easy-to-understand sentences is in itself a good rule of thumb when aiming to write well.

But it is only a rule of thumb, as I see it, and when it is enshrined as something more, it can do more harm than good.

The English language is a marvel of complexity and has so many rich, diverse, and colorful elements that you cheat only yourself as a writer if you fail to give full scope to such elements in choosing how to express yourself in the written word. You want to make a driving argument? By all means, use active verbs to punch along short, compact thoughts with an aggressive rhythm. Want to weave fascinating characterization? Well, then maybe relax the feel a bit and, with Dickens, unwind a string of long, flowing sentences that carry your reader along into a wonderfully imaginative series of pictures, running page after page, that hardly turn on being short, compact, and punchy - indeed, that are the very opposite. The point is not that you want to go to one extreme or the other. The point is that, as one who seeks to write well, you should avail yourself of the rich set of tools available to you without feeling bound to adhere to any form of absolute rules about how best to use them.

So, write away! Go for feel. Go for rhythm. Go for clarity. Go for what best suits your purpose.

And, oh, yes, do keep it short and simple, except when you find it doesn't suit your purpose. A rule of thumb is just that. In the end, do what gets your point across for the long-suffering reader who deserves to have it done well.

Because ambiguities in English sentences often cannot be resolved until the end,[1] readers tend to parse whole sentences before trying to fully understand them. Short sentences are a way of forcing readers to fully digest each thought before moving on to the next one.

Short sentences have additional benefits for persuasive writing (particularly legal writing). It's hard to hide anything in a short, simple sentence. Using them is a way of signaling your confidence in what you're saying.

[1] https://en.wikipedia.org/wiki/Garden_path_sentence

You’re right; to humans, short sentences do signal persuasive arguments and confidence in your ideas. And not without reason. People often speak longwindedly when they are trying to hide something.

But there is another reason someone might use long sentences. They might be trying to express a complicated idea. Sometimes an idea cannot expressed in a short sentence. Usually you can break up a complex idea into a few short sentences, but that might make the reading choppy and hard to follow. A long sentence leads its reader through the connections between ideas. In contrast, separate sentences express the ideas and leave it up to the reader to figure out what the connections are between the ideas.

This leaves us with an apparent cognitive bias: if we are distrustful of long sentences, we become distrustful of complex ideas.

Given this, I wonder if modern anti-intellectualism stems from this sensible defensive mechanism.

I don't think that's a cognitive bias. We should be inherently more suspicious of complex ideas. Complex ideas are more likely to be wrong than simple ideas due to the fact that their correctness rests on a greater number of assumptions.
I think there is an interesting parallel to code here. Its not uncommon for published algorithms to be ignored by practitioners in favor of simpler ones because of the perception that they are too complicated with too many corner cases. SSA-PRE comes to mind.
(comment deleted)
Writers are often advised to avoid long sentences. This is obviously wrong: the thing to avoid are complicated sentences. Long sentences can be simple if they don't require the reader to remember previous parts in order to parse the rest. Instead, each part extends the thought made in the previous one, with appropriate punctuation showing the relationship between the two; this sort of sentence can go on for lines without confusing anyone. A confusing sentence requires the reader to remember which verb was used forty words back, before it went off on a tangent. The cure for such sentences isn't simply bisecting them. Rearranging can bring separateed pieces of an idea together; if that doesn't work, one must drop the idea then explicitly take it up again later. Or, more brutally, axe the tangential remark. Not everything needs to be said, but if it does, say it somewhere else.

Seventy words shorter. I would have done the rest but I expired.

               Pedro comacho
 The former informer of the secret police
    Is still standing outside the club
         Pretending to be blind
    He watches the last plane to miami
  Disappearing in a flaming purple sky
             Now he knows
       He has been left behind
For those that missed the last plane to Miami (meaning all of you), the author was bitching that the rule in programming 'functions should be short, one page, etc' is as wrong as the rule that in writing sentences should be short.