×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Code Is Not Literature

Soulskill posted about 3 months ago | from the neither-are-tea-leaves dept.

Programming 240

An anonymous reader writes "Hacker and author Peter Seibel has done a lot of work to adopt one of the most widely-accepted practices toward becoming a better programmer: reading high quality code. He's set up code-reading groups and interviewed other programmers to see what code they read. But he's come to learn that the overwhelming majority of programmers don't practice what they preach. Why? He says, 'We don't read code, we decode it. We examine it. A piece of code is not literature; it is a specimen.' He relates an anecdote from Donald Knuth about figuring out a Fortran compiler, and indeed, it reads more like a 'scientific investigation' than the process we refer to as 'reading.' Seibel is now changing his code-reading group to account for this: 'So instead of trying to pick out a piece of code and reading it and then discussing it like a bunch of Comp Lit. grad students, I think a better model is for one of us to play the role of a 19th century naturalist returning from a trip to some exotic island to present to the local scientific society a discussion of the crazy beetles they found.'"

cancel ×
This is a preview of your comment

No Comment Title Entered

Anonymous Coward 1 minute ago

No Comment Entered

240 comments

Music... (2, Interesting)

Anonymous Coward | about 3 months ago | (#46028307)

...works much better as a model. Performing music is analogous to executing code.

Re:Music... (-1)

Anonymous Coward | about 3 months ago | (#46028363)

I hear your mom likes to be fucked by a pack of negro bulls to the music of Bach.

-- Ethanol-fueled

Re:Music... (4, Funny)

jellomizer (103300) | about 3 months ago | (#46028497)

Not as much, it is closer but not really.

The issue with Literature and Music there is a beginning, a middle and and a end.

With Software there is a beginning, then the story changes every time the program runs, based on the input at the time. Leading to multiple end points, including a power off.
Music is closer as it had notation that allows for some loops, however this is mostly to keep shorten the notation process and less about workflow.
Also a choose your own adventure book, isn't that good analogy, as there are fixed number of stories possible.
A relatively complex program can have different outcome all the time.

Re:Music... (0)

Anonymous Coward | about 3 months ago | (#46028891)

enumerable possibilities, indeed.

Re:Music... (2)

camperdave (969942) | about 3 months ago | (#46028945)

Never read a "choose your own adventure" did you?

Re:Music... (2)

ShanghaiBill (739463) | about 3 months ago | (#46029119)

Never read a "choose your own adventure" did you?

"Choose your own plot" books have a very limited number of choices. The number of possible paths through code increases exponentially with the size of the program. Literature usually has the meaning the author intended. If you are reading code, it is usually because it does NOT do what the author intended.

Similar language, describing different things (2)

hessian (467078) | about 3 months ago | (#46028313)

Code is very similar to language. How would it not be?

However, what's being described is entirely different. A narrative relies on both clear expression of the action and a broad context of details to give it resonance.

Code, on the other hand, operates through loops and definitions independent of timeline, so is a better match for architecture and math than the science of communications.

Re:Similar language, describing different things (0, Troll)

Anonymous Coward | about 3 months ago | (#46028403)

This is just a pathetic attempt to address the fact that boring, drab Computer Science-studying robo-humans devoid of personality still cannot complete against the broke poets and other Liberal Arts majors for female attention.

*Comes running up* ...hey Lisa *wheeze* Look at this, code I wrote, look how "deep" it is! I can do art too! I will write poetry for a living!

-- Ethanol-fueled

Re:Similar language, describing different things (1, Funny)

Anonymous Coward | about 3 months ago | (#46028531)

This is just a pathetic attempt to address the fact that boring, drab Computer Science-studying robo-humans devoid of personality still cannot complete against the broke poets and other Liberal Arts majors for female attention.

You're doing it wrong. Just open up your wallet. The art women appreciate most is green ink on a cotton paper with a portrait of Benjamin Franklin.

Re:Similar language, describing different things (-1)

Anonymous Coward | about 3 months ago | (#46028731)

Actually I reconsidered, females don't attract me.
I love the cock!

-- Ethanol-fueled

Re:Similar language, describing different things (1)

ElectricTurtle (1171201) | about 3 months ago | (#46028841)

As somebody who has detested Ethanol-Fueled since the time when he posted under his actual account before becoming afraid of his bad karma, I thank you AC.

Re:Similar language, describing different things (4, Insightful)

JoeMerchant (803320) | about 3 months ago | (#46028547)

I've always been struck by the similarity of code and contracts or laws.

When written well, they define a set of requirements for specific actions to take place, leaving no ambiguity.

When written poorly, you need to know the version of system they are running under, starting circumstances, state of concurrently running processes, etc.

Re:Similar language, describing different things (4, Insightful)

Marxist Hacker 42 (638312) | about 3 months ago | (#46028573)

Correct. And just like laws- if regular people can't read what you have written, then likely you are doing it wrong.

Bad law is always overly complex. The more complex it is, the more likely somebody has introduced some ambiguity.

Bad code is also always overly complex. The more complex it is, the more likely it will take a week to do a job that should take an hour when maintaining it.

Re:Similar language, describing different things (2, Interesting)

Anonymous Coward | about 3 months ago | (#46028645)

if regular people can't read what you have written, then likely you are doing it wrong.

That seems like a stupid standard. What if that "regular" person simply has no experience in what you wrote? If I write perfectly good SIMD assembly and this mythical "regular" person can't read and follow it because they are unfamiliar with x86 MMX/SSE/AVX how is that my fault and why would that me my code bad?

Re:Similar language, describing different things (3, Insightful)

JoeMerchant (803320) | about 3 months ago | (#46028897)

If you are writing assembler, you _should_ be including a human readable commentary at some level.

If you have put 5000 assembly instructions under a heading titled "object rotation and zoom", with no other commentary, your code _should_ be expelled from the system, regardless of how well it works on the test cases you made up for it.

Re:Similar language, describing different things (0)

Anonymous Coward | about 3 months ago | (#46029107)

Sure and it would be, but it's still likely it would be very hard to understand by a "regular" person with no previous experience in either the language or in DSP. So, again, how is their lack of understanding mean that my code is bad?

Re:Similar language, describing different things (0)

Anonymous Coward | about 3 months ago | (#46029157)

Human readable commentary is helpful but only if the assembler programmer wasn't a fucken idiot.
Small sample of actual comments I've seen:
1. If you don't know what this does then fuck-off
2. Bla bla bal, what more do you want to know?
3. My boss is a ass-hole!
4. If you are reading this then get a life
5. Got C ?

Re:Similar language, describing different things (4, Interesting)

Stormy Dragon (800799) | about 3 months ago | (#46028775)

Please demonstrate a basic sorting algorithm that a non-programmer can understand that doesn't perform terribly on large lists. You might be able to write a bubble or insertion sort that makes sense to a layman, but for the majority of the population something like mergesort, quicksort, or heapsort is going to seem like voodoo no matter how elegantly it is coded.

Re:Similar language, describing different things (2)

JoeMerchant (803320) | about 3 months ago | (#46028925)

When I use voodoo, I usually include hyperlinks to Wikipedia or similar sources explaining what's going on. Even when the links die, you can usually search on the algorithm names to come up with an explanation.

More often, I let the library deal in the voodoo and my code reads like: while ( input ) { insert } sort.

Re:Similar language, describing different things (1)

MetalOne (564360) | about 3 months ago | (#46028933)

quicksort [] = [] quicksort (x:xs) = quicksort [y | y x]

Re:Similar language, describing different things (1)

MetalOne (564360) | about 3 months ago | (#46028955)

Should have paid attention to the preview, dang it.
quicksort [] = []
quicksort (x:xs) = quicksort [y | y x]

Re:Similar language, describing different things (1)

MetalOne (564360) | about 3 months ago | (#46028967)

Slashdot messed up my post. Well, it was meant to be the 2 liner Haskell quicksort.

Re:Similar language, describing different things (0)

Anonymous Coward | about 3 months ago | (#46029139)

And how exactly does being only two lines long make something understandable to a layman?

Re:Similar language, describing different things (1)

Anonymous Coward | about 3 months ago | (#46029137)

* that doesn't perform terribly on large lists *
This is shit code and will perform like utter shit in the real world because of all the copying and strict, forward-only iteration. It's also misnamed. If you weren't an idiot, you'd know that quicksort is an in-place sort and the garbage you just posted isn't. May as well fucking insertion sort; it'd be faster.

This is why no one takes anyone who advocates Haskell seriously.

Re:Similar language, describing different things (2, Informative)

Anonymous Coward | about 3 months ago | (#46029011)

How about sorting a deck of cards using two of the algorithms you mentioned, quicksort and mergesort.

Quicksort: Take a deck of cards, and pick a random card. Form two new decks by placing all cards smaller than it to the left deck and the larger or equal ones to the right deck. Repeat this for both decks, so you get more decks. Never move a deck over another. At the end just combine the decks from left to right in increasing order.

Mergesort: 1. Place all cards on the table, each on its own slot. If there's not enough space, form decks of five cards each and sort them manually. 2. Take the two piles with the least cards in them (or close enough, doesn't matter). Find the smallest card in the two piles, and put it on the table. Put the next smallest table on top of the previous one, and so on, until there are no cards left. Leave the resulting pile on the table and continue from 2.

Of course, a non-organized person might mess the decks, but others should be able to understand these. These instructions should give the correct asymptotic running times, assuming for example that the person realizes finding the minimum is quite simple when the decks are sorted.

Re:Similar language, describing different things (3, Insightful)

Stormy Dragon (800799) | about 3 months ago | (#46029059)

1. My point is not about how to teach someone how quicksort. It was refuting the commenters assertion that any code not understandble to regular people is bad code. Your quicksort.c file is not going to pick up a deck of cards and demonstrate what it's doing.

2. I'm betting that for 60% of the population out there, they still would not understand how quicksort works after your card demonstration.

Re:Similar language, describing different things (4, Informative)

hamster_nz (656572) | about 3 months ago | (#46029223)

but for the majority of the population something like mergesort, quicksort, or heapsort is going to seem like voodoo no matter how elegantly it is coded.

Explaining quicksort to the layman.

Here's a 1000 names on little cards. Pick one at random and look at the name.

Sort the names into three piles - those that come earlier in the list, those that are the same as the name, and those that come later than the randomly selected name name.

Put the "earlier" pile to the left of the "same" pile, and then put the "later" pile to the right of these two.

Great? Done that?

Now repeat on the process on each "earlier" and "later" piles, Do this over and over again, giving you smaller and smaller piles. It doesn't really matter which pile you split first, just as long as you don't mix up the relative left/right ordering.

Eventually you will end up with lots of small piles of cards that contain all the entries of the same name.

And then, as if by Voodoo., all your names are now in order from left to right.

This can be parallelised - if you want, you can out-source some of the work to friends and family, to speed things up.

Re:Similar language, describing different things (2)

Sique (173459) | about 3 months ago | (#46029061)

Bad laws don't need to be overly complex. Bad laws are just that: bad. You can have very simple laws which in general create a bad outcome.

Re:Similar language, describing different things (1)

Anonymous Coward | about 3 months ago | (#46029087)

Define "regular person". If you're referring to the same general crowd that doesn't know how to make Windows prompt them for updates instead of auto-rebooting, you're asking far, far too much.

Re:Similar language, describing different things (1)

buchner.johannes (1139593) | about 3 months ago | (#46028931)

So Gamebooks [wikipedia.org] are not literature then?

Re:Similar language, describing different things (0)

Anonymous Coward | about 3 months ago | (#46029063)

If you were reading a pick-a-path book with an eye towards determining why opening the door should take us to page 32 instead of 33, 34 or 89, then you'd appreciate the literary content less.

Slashdot is for niggers (-1, Troll)

niggers sucking cock (3506657) | about 3 months ago | (#46028323)

You are all fucking bastards who need to get raped by horses

Re:Slashdot is for niggers (0)

Anonymous Coward | about 3 months ago | (#46028341)

Welcome back. Have you been on vacation or in the slammer?

Re:Slashdot is for niggers (0)

Anonymous Coward | about 3 months ago | (#46028401)

smit is that you?

Re:Slashdot is for niggers (0)

Anonymous Coward | about 3 months ago | (#46028463)

welcome to /chan .... *facepalm*
the support group for in-bread neo nazi survivors of horse rape is over at stromfront , here is where the adults are talking so stfu and go back to your google image searches for BBC ....

Re:Slashdot is for niggers (1)

Desler (1608317) | about 3 months ago | (#46028489)

Neo Nazis are in bread now? White, wheat or whole-wheat white?

Re:Slashdot is for niggers (2, Funny)

Anonymous Coward | about 3 months ago | (#46029189)

obviously white-only

What? (1)

TechyImmigrant (175943) | about 3 months ago | (#46028331)

Since when was I required to do code reading as an exercise? I've never heard of such a thing.

Can people stop inventing stupid new things I must do to be the perfect programmer?

Do not invite me to your code reading club. I'll decline the invitation.

Re:What? (4, Insightful)

Dan East (318230) | about 3 months ago | (#46028471)

The must instructive, enlightening thing I did in college while majoring in CS was to take a part time job grading Pascal assignments for an instructor. Of course my programming experience was significantly above that of the class being taught, but it was still very worthwhile to see how different minds went about solving a specific problem. There were a few students who I could immediately identify (by their code) who had the proper thought process (whether learned or innate - most likely the latter) for software development. I could easily recognize a few groups of 2-3 students who had obviously collaborated on the assignment (it was supposed to be an individual assignment). Students who only knew the most rudimentary constructs of the language were obvious - for example relying on huge sets of if / else statements instead of a simple case statement. There's just something about "reading" and critiquing code that makes you more self aware of the code you produce. Whether we're talking about code efficiency, style, organization or conciseness - I found myself writing better code (again, and not even necessarily through example or having seen something new) after having spent time grading and critiquing others' source code.

Re:What? (5, Insightful)

Anonymous Coward | about 3 months ago | (#46028619)

Reading other people's code is a great way to learn better ways of doing things you thought you already knew how to do. ;)

Re:What? (4, Interesting)

cold fjord (826450) | about 3 months ago | (#46028713)

Your comment reminds me of this bit about the code for what became Adobe Photoshop. The code is available for download from a link on the page linked to below.

Adobe Photoshop Source Code [computerhistory.org]

Thomas Knoll, a PhD student in computer vision at the University of Michigan, had written a program in 1987 to display and modify digital images. His brother John, working at the movie visual effects company Industrial Light & Magic, found it useful for editing photos, but it wasn’t intended to be a product. Thomas said, “We developed it originally for our own personal useit was a lot a fun to do.” Gradually the program, called “Display”, became more sophisticated. In the summer of 1988 they realized that it indeed could be a credible commercial product. They renamed it “Photoshop” and began to search for a company to distribute it. ... The fate of Photoshop was sealed when Adobe ... decided to buy a license to distribute an enhanced version of Photoshop. ....

Commentary on the source code
Software architect Grady Booch is the Chief Scientist for Software Engineering at IBM Research Almaden and a trustee of the Computer History Museum. He offers the following observations about the Photoshop source code:

“Opening the files that constituted the source code for Photoshop 1.0, I felt a bit like Howard Carter as he first breached the tomb of King Tutankhamen. What wonders awaited me? I was not disappointed by what I found. Indeed, it was a marvelous journey to open up the cunning machinery of an application I’d first used over 20 years ago. Architecturally, this is a very well-structured system. There’s a consistent separation of interface and abstraction, and the design decisions made to componentize those abstractions – with generally one major type for each combination of interface and implementation — were easy to follow. The abstractions are quite mature. The consistent naming, the granularity of methods, the almost breathtaking simplicity of the implementations because each type was so well abstracted, all combine to make it easy to discern the texture of the system. . . .

This is the kind of code I aspire to write.”

Good examples can provide powerful learning experiences. They can crystalize the intangible aspects of description and discussion.

Re:What? (1)

Anonymous Coward | about 3 months ago | (#46028503)

You're not required to do anything. On the other hand, refusing to be open to learning something new (in this case, how other people solve problems) is close to willful ignorance.

Re:What? (0)

Anonymous Coward | about 3 months ago | (#46028615)

Code reading is part of one of my University modules. The module is 3 years old and close to being it's final.

It's not a new skill and it's very useful.

Re:What? (0)

Anonymous Coward | about 3 months ago | (#46028637)

Not to worry, you're name was never mentioned for any of the invite lists... :)

Re:What? (1)

Anonymous Coward | about 3 months ago | (#46028961)

Oh Dear, "TechyImmigrant" is proving that outsourcing is still a terrible idea.

What were they doing before? (1)

kruach aum (1934852) | about 3 months ago | (#46028345)

Discussing the meta-narrative implied by errant GOTO statements? Considering the motivations of while loops? Debating the thematic development in variable naming schemes?

Learning from anything means analyzing it, knowing what goes where for what reason, and then thinking about if there are other ways to do it, better ways to do it, if it needs to be done at all, etc. When you're reading with the intent to understand and you're doing something that's not appreciably different from simply 'viewing words' you're doing something wrong.

Re:What were they doing before? (4, Funny)

bob_super (3391281) | about 3 months ago | (#46028465)

By the time some of my literature teachers are done, I'm sure the Hello World would be a subtle and poignant take on the overbearing consumerism as well as taking us to the depths of despair in search of the hero's hidden personality fractures.

Re:What were they doing before? (5, Funny)

Anonymous Coward | about 3 months ago | (#46028477)

It's more about the metatextual narrative. What does this say about the author? This GOTO implies that the author does not want to be where he is. He is desperate to break out; to be anywhere other than where he is now. He's backed himself into this corner, bound in a loop of his own devising, and yet unable to meet the conditions necessary to move forward. "GOTO!" he cries out, "For the love of God, take me away from the endless DO and WHILE!"

Here we see laid out the mind of a soul utterly broken. Can you not feel his burning shame? From the time he first took his toddling steps into the Hello, World! his teachers have admonished him "GOTO statement considered harmful". Yet desperate times call for desperate measures. He casts the thread of his execution into the void*.

Where will he land? We scan the page with increasing alarm. Can you feel your heart quicken? Where is the label? Where are we GOing TO? Now the reader is caught up in the narrative as well as the author. Does the label exist at all? How did this thing ever compile? Until finally, we see it. Safe at last! Our execution can continue, and yet we are forever changed by the experience. Have we exited the loop in the correct condition? Will there be enduring side effects? Read on to find out...

* The void, that is, not a pointer to an unknown type, I just mean to clarify that as a footnote**.

** A footnote, that is, not a pointer to a pointer to a footnote.

Re:What were they doing before? (1)

kruach aum (1934852) | about 3 months ago | (#46028527)

If I hadn't already taken part in this discussion I would upvote you. ""GOTO!" he cries out," is a brilliant line and should really be the opening of 'Waiting for GOTO'

Re:What were they doing before? (5, Funny)

gstoddart (321705) | about 3 months ago | (#46028639)

Discussing the meta-narrative implied by errant GOTO statements?

The GOTO statement is reflective of the existential malaise experienced by programmers, and typified in post-modern society.

It shows that the programmer in the code, as in life, feels they have reached a dead-end from which there is no escape, and reflective of a desire to escape the mundane and return to the optimism of youth.

The GOTO becomes a metaphor for man's desire for a quick solution to our problems, and a naive belief we can make the problems go away, and thus becomes symbolic of wish-fulfillment and fantasy to offset the feelings of stagnation and dread so often described in post-modernism.

In stack based languages, the GOTO becomes a surrogate for a strong father figure, and metaphorically kills the mother in frustration. It's also convenient for breaking out of nested logic to an error handler, which gives us feelings of going back to the womb, and indulging in self-infantilism in order to achieve a more expedient resolution of the dichotomy between self and other.

Thematically, the GOTO is both liberation, and the source of our own slavery; it simultaneously demonstrates our desire for freedom, as well as showing the futility of such a quest and how we re-enslave ourselves through our actions.

Because it highlights the existential question of "how do you implement an IF statement without a GOTO in Assembler?", it forces us to acknowledge that, as much as man tries to escape his primitive roots, there persist behavior which is neither rational nor defensible, but which we nonetheless cannot do without from an evolutionary perspective.

The GOTO defines for us the boundary between man as thinking entity, and non-thinking animal. And, as in Conrad's Heart of Darkness, forces us to look within ourselves, and confront the things we see but cannot fully understand or control.

The real problem is... (-1)

Anonymous Coward | about 3 months ago | (#46028357)

... revealing the structure of a program in text is moronic, they should be translating it into visual forms like circuits and graphs. Just seeing a bunch of lines like int x = 10 plus whatever screwed up naming conventions the authors of programming languages came up with obscure the fundamental fact that programs are diagrams regarding the flow of information in a circuit. I've imagined converting the text to something we can all naturally understand like sewer pipes and flows of water (data) in the third dimension.

The reality is building programs via text while handy is not the best way to analyze them.

Re:The real problem is... (0)

Anonymous Coward | about 3 months ago | (#46028689)

I've imagined converting the text to something we can all naturally understand like sewer pipes and flows of water (data) in the third dimension.

You and many others. But people keep reinventing Labview, and it's always a bit of a mess. Not to mention change review and source control!

If you're really interested in that kind of abstraction you might want to take a look at Haskell with arrows and monads.

Code as a tool of thought? (2)

DavidHumus (725117) | about 3 months ago | (#46028361)

There is a (rather small) minority view that code can actually improve our ability to think - http://www.jsoftware.com/jwiki... [jsoftware.com] . However, the bulk of opinion sees code as an obstacle to be overcome - rightly so, given the sloppy, ad-hoc construction of most programming languages.

That's interestingly backwards (2)

kruach aum (1934852) | about 3 months ago | (#46028451)

Code itself is simply a set of rules tying words and symbols to operations on a system. Learning those rules won't make you better at anything but learning rules. What will help you develop as a thinker is learning the underlying theory and ideas of a closely related field -- computer science. Thinking up your own solution to the dining philosophers problem, the knapsack problem or even understanding how you can describe the solution to the towers of Hanoi as an iterative process all help you develop problem solving skills and grant deeper insight into solving other problems. Simply learning a new coding language (unless that language is interestingly 'conceptually' (for lack of a better word) different from one you already know, like learning LISP when all you know is BASIC) won't improve much.

Re:That's interestingly backwards (2)

darkwing_bmf (178021) | about 3 months ago | (#46028737)

Hogwash. One of the fundamentals of programming is understanding the machine or system and the "rules" for controlling it. How are you to develop an algorithm for solving the towers of Hanoi on a specific system if you don't know whether or not that system is capable of recursion (or perhaps even requires it)? How are you going to handle input and output without knowing the "rules" for the interfaces? High level algorithms can be solved by mathematicians but computer scientists use "rules" to make the machines do what they want. There is no computer science without the "rules".

Re:That's interestingly backwards (1)

DavidHumus (725117) | about 3 months ago | (#46029129)

This is an extremely blinkered view of code that probably well-represents the majority opinion, given that that's the genesis of most programming languages.

However, there is a small group of languages that aspires to represent computational concepts at an abstract level in a clear, consistent, and logical manner. These languages, like APL and J, are based on a regularization of mathematical notation.

80/20 rule (1)

SQLGuru (980662) | about 3 months ago | (#46028419)

80% of the code of a program is uninteresting and mundane. As a programmer, you want to get to the core nugget of a problem, suss it out and solve it. "Reading" code is the same thing. You want to decode the structure, find the interesting 20% and move on to gleaning whatever you can from it. It's in our nature.

Consider your Audience when writing code (4, Insightful)

DickBreath (207180) | about 3 months ago | (#46028441)

When writing code, your audience is not the compiler.

Your audience is another human being who will be maintaining that code a few years later.

If your audience were the compiler, then your code would just need to compile and run. It could be ugly. Unreadable. Unmaintainable. Uncommented. Have meaningless identifiers. Poor organization. Follow worst practices. Etc. In short, the kind of code you get from an outsourced contractor.

Consider that another human is your audience. Choose identifiers such that a comment is unnecessary. Comments should not say what is obvious. (This assigns foo to x.) Comments should say what is not obvious and cannot be made obvious by the code itself.

Write your code almost as if you are writing literature.

Re:Consider your Audience when writing code (1)

Alomex (148003) | about 3 months ago | (#46028505)

When writing code, your audience is not the compiler. When writing code, your audience is not the compiler.

Sir, I'm a member of the language police and I just pulled you over for a stupid over generalization for effect infraction.

Your audience is of course both the compiler and the other human being maintaining the code after you. A good programming language walks this fine line. Prolog was too much on the human side, Perl is too much on the interpreter side.

Re:Consider your Audience when writing code (3, Insightful)

DickBreath (207180) | about 3 months ago | (#46028585)

The programming language is irrelevant. Bad code can be written in any language. Really good code is an art in any language.

The compiler is not an audience at all. The compiler is the first part of running the code. As far as the compiler is concerned, the code could be obfuscated.

That fact that the code performs it's function is the first economic value of the code. But an equally large, and perhaps greater economic value (or cost) is how well another human can read and comprehend that code later on when managers decide to add pointless features or remove useful features.

Most code is written for economic reasons of some type. Writing code for another human to easily comprehend later increases the economic value of that code -- possibly greatly.

Re:Consider your Audience when writing code (1)

Alomex (148003) | about 3 months ago | (#46028807)

Bad code can be written in any language.

And this in no way contradicts that some languages are better than others for that purpose. For a simple example consider the original COBOL syntax of

ADD 1, N GIVING N

This is sucky, harder to read code than n := n+1 or n++

As far as the compiler is concerned, the code could be obfuscated.

You have no idea how compilers operate if you believe this. The compiler is interested for example, in teasing apart dependencies so it can apply optimizations. Here's an example of badly written code in terms of the compiler:

If Test(Water, Wet) then
  blah

the compiler will be unable to see that the first call always succeeds and pipeline its execution.

Another example, things such as side-effects are bad for the programmer and are bad for the compiler so just clarifying them for the programmer is not enough, e.g.


x = f(object y) // function f touches variable z deep inside the methods of object y
print z

So the comment makes this perfectly clear to the programmer but not to the compiler.

Re:Consider your Audience when writing code (1)

Obfuscant (592200) | about 3 months ago | (#46029125)

And this in no way contradicts that some languages are better than others for that purpose. For a simple example consider the original COBOL syntax of ADD 1, N GIVING N This is sucky, harder to read code than n := n+1 or n++

Algebraic notation is easier if you know algebra and that it really isn't algebra despite the similar appearance. "n++" in particular requires knowledge of pre and post increment ops. The COBOL, on the other hand, is almost English. If English isn't your language COBOL is hard.

And I still remember the elegance of the:

MOVE CORRESPONDING A TO B.

COBOL syntax. It was a very fresh alternative to other early languages where you had to do this operation one field at a time. And if you modified the struct but forgot to add the copy of the new field every place you copied the old, you made bugs.

x = f(object y) // function f touches variable z deep inside the methods of object y
print z

If you have made z a global so that it is in scope for function f as well as the main code the compiler will know this, as will the programmer.

Re:Consider your Audience when writing code (1)

gstoddart (321705) | about 3 months ago | (#46028815)

When writing code, your audience is not the compiler. When writing code, your audience is not the compiler.

Sir, I'm a member of the language police and I just pulled you over for a stupid over generalization for effect infraction.

Well, as another member of the language police I'm required to remind you that including the quote twice for effect is a breach of hyperbole rule #17-c, and is, in effect, an equivalent infraction.

Your section chief has been notified, and you will be required to take language remediation module 763.3.a. ;-)

Re:Consider your Audience when writing code (2)

Cro Magnon (467622) | about 3 months ago | (#46028541)

Consider that another human is your audience. Choose identifiers such that a comment is unnecessary. Comments should not say what is obvious. (This assigns foo to x.) Comments should say what is not obvious and cannot be made obvious by the code itself.

That's one of my peeves. When I see a comment like that, I scream (usually silently) that I know you're assigning foo to x. I want to know WHY you're assigning foo to x!

Re:Consider your Audience when writing code (3, Funny)

DickBreath (207180) | about 3 months ago | (#46028649)

> That's one of my peeves. When I see a comment like that, I scream . . .

When someone does it, then put the following optimizations into their header files somewhere. Be sure to include the useful comments that explain their purpose.

#define struct union // optimization to use less memory
#define while if // optimization to make code run faster

It's the thought that counts.

Re:Consider your Audience when writing code (1)

phantomfive (622387) | about 3 months ago | (#46028953)

. When I see a comment like that, I scream (usually silently) that I know you're assigning foo to x. I want to know WHY you're assigning foo to x!

Sometimes I mischievously add comments like that to the code, just because I know how happy it will make some people. //explain why I add comments like that to code

Re:Consider your Audience when writing code (4, Insightful)

HeckRuler (1369601) | about 3 months ago | (#46028609)

Your audience is another human being who will be maintaining that code a few years later.

And he's a violent psychopath who knows where you sleep at night.

Re:Consider your Audience when writing code (1)

phantomfive (622387) | about 3 months ago | (#46028905)

Your audience is another human being who will be maintaining that code a few years later.

And he's a violent psychopath who knows where you sleep at night

This quote is currently on our whiteboard at work right now.

Re:Consider your Audience when writing code (3, Insightful)

Ichijo (607641) | about 3 months ago | (#46028659)

Your audience is another human being who will be maintaining that code a few years later.

Or yourself a few weeks later, if you're getting old like me and can't remember why you did what you did. This is also why I make an extra effort to ensure the code works the first time, with the fewest possible side effects, so I don't have to maintain it later.

Re: comments (0)

Anonymous Coward | about 3 months ago | (#46028767)

"Comments should say what is not obvious and cannot be made obvious by the code itself."

Comments should explain the WHY, not the WHAT.

e.g. /* cannot do <obvious first choice> because <explanation> */ or /* X can never be Y because <proof> */

tool, not primarily communication (0)

Anonymous Coward | about 3 months ago | (#46028447)

Code is a tool someone has built. It is not an attempt at communication. It is a language in a similar sense that mathematics is a language.It has more in common with a building or a car than a work of literature.

Re:tool, not primarily communication (2)

DickBreath (207180) | about 3 months ago | (#46028475)

If that tool you speak of is static and unchanging, like a wrench, then I could agree with you. Even if it were a moderately complex but extremely common machine with standardized parts, like a car, I could agree.

But if that tool is a complex machine, even a software machine, then communication is an important goal. Software inevitably requires maintenance and will be changed and improved over time. Pointless features will be added. Useful features removed. Since this machine is not an off the shelf machine, like a car, it is important that all of the information that the maintainers and improvers need are somewhere. The best place is probably in the source code itself.

Re:tool, not primarily communication (1)

phantomfive (622387) | about 3 months ago | (#46028895)

Code is a tool someone has built. It is not an attempt at communication.

If code were not an attempt at communication, we wouldn't care about readable variable names. A lot of the advances in programming language technology are there, not for the benefit of the computer, but for the benefit of the person who will come after you. They will need to read your code.

Yeah I Could See That (4, Interesting)

Greyfox (87712) | about 3 months ago | (#46028485)

I've read a lot of code over the years and thinking back on it, I do kind of approach it that way. What I'm doing feels more akin to taking a machine apart to see how it works rather than reading it as I would a book. I often feel, when I'm interrupted, like I'm ass-deep in wires that are going every-which-way.

It is still a method of communication, though. You can often tell a lot about the programmer and his state of mind at the time by reading his code. It's very easy to tell when they were confused about what they were trying to accomplish, how comfortable they were with the language they were using and whether or not they were in a hurry.

Early on in my career, I started with the assumption that the original programmer knew what he was doing. The more code I read, the more I realized that this is almost never the case. From my observations, it takes about a year for someone to come up to speed with a project, the business process for the company they're working at, and any code base that was already there. Longer if the company's business processes suck. Until then they're mildly to severely confused, and this is reflected in their code. Since a lot of programmers don't hang around at one company for much longer than that, most of the code that I've run across has been crap. The first inclination might be to rewrite it, but as you're starting on a new project you're also mildly to severely confused, so it's best just to study the crap closely and make minor improvements as the opportunities arise. A crap in the hand is worth two in the bush. Or something. Most of the time. I've run across a couple of what had to have been bottom-ten-percent programmers whose crap did end up requiring full rewrites. Coming into a C project where the programmer didn't realize strings are null terminated is a huge warning. C++ or Java code where everything inherits from everything else is also a warning.

Code is like literature (1)

Walter White (1573805) | about 3 months ago | (#46028491)

I disagree completely. A program resembles literature on two levels.

First, the code itself uses an extremely rigid grammar to express the requirements of the program. This expression can be simple or complex; clear or muddled. The extent to which the author (in every sense of the term) expresses these clearly and elegantly determines how likely the code is to succeed at its original purpose as well as how easy it will be to maintain.

Secondly, the UI (if present) is also a realization of the ideas behind the program. The clarity with which the ideas are expressed in the UI will have a major impact on the usefulness of the program.

I do not see a fundamental distinction between decoding code and written language. Both are abstract symbols assembled to form constructs and actions according to a set of more or less flexible rules. Many of the higher parts of language such as metaphor also have corresponding aspects in coding. (e.g. patterns.)

And much like with literature which can be written in a multitude of languages, code can likewise be written in a multitude of languages. I think there are more similarities than differences.

Crazy beetle ecosystem (1)

Chemisor (97276) | about 3 months ago | (#46028569)

Complex code is not just a specimen. It is an ecosystem, where your crazy beetle consumes crazy aphids and evades crazy ants, while simultaneously trying to reproduce itself and the entire ecosystem to the best of its ability. A crazy beetle would not eat anything standard, like say make or autoconf. No, his refined palate requires a more sofisticated tool like imake, cmake, or even an internally grown food made of ground up pythons. Eating and reproduction habits may also be equally crazy all on their own. For example, crazy beetle firefox can only reproduce when confined in a clean chroot with every consumable painstakingly arrange exactly like he wants it. Other crazy beetles sometimes refuse to eat when certain other crazy beetles are present. When let loose in an unfamiliar environment, crazy beetles sometimes quietly die for no apparent reason and intensive investigation may be required to uncover the cause of their demise. A biology degree may be helpful in such circumstances.

Re:Crazy beetle ecosystem (0)

Anonymous Coward | about 3 months ago | (#46028917)

It's funny that you mention autoconf, which was one of the first crazy beetles.

Use make *without* autoconf. Have a config.h file or ${platform}/{Makefile,config.h,platform_feature_foo.c} files if your code has legitimate porting issues. Don't attempt to anticipate portability problems, just deal with them if they arise, because more often than not, they don't. When you go chasing "ghosts of Ultrix past" you invite in all sorts of portability problems that have long since been evaporated.

"'Portable' programs tend to be the most difficult programs to port."

-puddingpimp

Well parts are like literature (3, Interesting)

HeckRuler (1369601) | about 3 months ago | (#46028571)

No no, certain parts of coding is very much like literature. The style of how you... branch based on a string, or how you implement event-driven coding, or how you distribute computing power.
There are a TON of ways to skin those cats and which way you do it is a matter of stylistic preference. It's fashion. The exact sort of subjective shindig that lit major whittle away their time with. It's like the difference between writing in first person or third person. And in certain places one way is very much better than the other.

But who the hell reads code for the stylistic appreciation? We read code because it's broken, we want to steal part of it, or we need it to do something else. That's not a stylistic issue, that's a mechanic wrenching on a car. Figuring out just what the hell it's doing is a different act than bickering how it could have been done better. Doing the first part pays a lot better than the second.

This guy has noticed that most people that read things are reading restaurant menus, technical documents, text books, grocery lists, and not novels. The writers of said material are doing it to get shit done rather than fretting about how they do it.

Re:Well parts are like literature (4, Interesting)

Greyfox (87712) | about 3 months ago | (#46028799)

But but but! A mechanical object can be beautiful, and so can code! Often I've seen brilliant and occasionally sadistic approaches to the problem that I can definitely appreciate at an artistic level. Something like Duff's Device [wikipedia.org] requires both technical brilliance and a good amount of creativity. I have to read and analyze code for my job on a regular basis.

A mechanic must know his way around a car to know how to repair it, and I must know my way around the code base if I am to diagnose problems. I can't just focus on the broken parts of it, or changes I make will likely introduce side effects. On most of my projects I didn't even have a requirements document, just a big pile of usually-poorly-written code. Each program is a unique individual machine, as if every single car were built dramatically differently. How much harder would it be for a mechanic if they had to go hunting for the spark plugs before they could even get started?

As a Literature Major/Programmmer ... (1)

machineghost (622031) | about 3 months ago | (#46028577)

As a Literature Major/Programmer, let me start by admitting the obvious: of course code is not literature, it's code. That being said, there is far more in common between the two than most programmers realize. Just as you can write an essay that's easy to understand and follow, or hard, regardless of the topic of the essay, so can you write code that easy/hard to grok regardless of what it actually does.

In both cases a good writer tries to make the subject matter accessible to the reader, precisely so that they *don't* have to go on a scientific expedition just to grok it.

Re:As a Literature Major/Programmmer ... (0)

Anonymous Coward | about 3 months ago | (#46028739)

Essays are not literature. Literature is (a certain hifalutin variety of) fiction.

Re:As a Literature Major/Programmmer ... (0)

Anonymous Coward | about 3 months ago | (#46029067)

And both can be explored on superficial and deeper levels.

Well written things should be grok'able at the top layers, but both are likely to require study/analysis to understand fully what they say.
The more effort put in to the writing, the more that can be gotten on the early passes.

Still code is code and requires a different set of skills to read than literature.
    The same could be said for English versus Russian literature.
        Both because of the language and cultural nuances.

The article focused on the differences, but didn't acknowledge the similarities.
      This perhaps falsely made the conclusion seem stronger than it was.
     

An unusual exercise ... (1)

Grindalf (1089511) | about 3 months ago | (#46028591)

No one, but NO ONE likes to work with someone else's code. It's bad news when you have to do this at work. It's much more effective to rewrite the job from scratch after planning the functionality, encapsulation etc. etc. again. So to most people this type of job (whether it's like a line by line dissemination of a machine code tome or whether it's like an insectoidal dissection) is an unusual and unpracticed chore.

Re:An unusual exercise ... (0)

Anonymous Coward | about 3 months ago | (#46029099)

No one, but NO ONE likes to work with someone else's code.

The success of open source development seems to indicate otherwise.

Code Tactics (0)

Anonymous Coward | about 3 months ago | (#46028663)

I examine code much like I study chess tactics. When should I use pointers, smart pointers, or garbage collectors? What are the methods and advantages of using different paradigms? When I read other people's code I'm constantly examining and criticizing their choices and implementations. If I find something that works better than what I'm doing I change my habits. It's not like sitting down and reading a book; its more like trying to solve a chess puzzle.

Clean code is another matter entirely. All code should be written for the next programmer to be able to easily digest its intent and function, but making code easy to read over its functionality should be a programming sin. Not using threads because its harder for the next guy to debug is not an acceptable practice. If the code is not cleanly and clearly written it is very difficult to divine its true purpose.

Wrong model (1)

gweihir (88907) | about 3 months ago | (#46028711)

Unlike literature, Art, music, etc., code has very little redundancy. In fact, low redundancy is a quality measure for code. Hence "reading" is an entirely unsuitable approach, as "reading" relies on relatively high redundancy on all layers.

IMO somebody that does not understand this beforehand does not have any real understanding of what code is.

you don't read it? maybe (0)

Anonymous Coward | about 3 months ago | (#46028789)

Plain English (a movement by the osmosian order) is a selfcompiling programming language composed of literally plain english

I don't see how any programmer would think that (3, Interesting)

istartedi (132515) | about 3 months ago | (#46028863)

I don't see how any programmer would think code was literature, except perhaps highly technical literature. You read novels from beginning to end. You read code on an as-needed basis. You might only read the header of a library. In fact I've seen good libraries where the only docs I read were long comments in the header file. If you want to understand a system you might start with main() or your language's equivalent and find some kind of dispatch function with calls to things like ResizeWindow which is *boring* and calls to things like DetectThief which is *interesting* so you drill down into the DetectThief function and find out where it gets the data and how it decides the user might be a thief. That might only be a few thousands lines that you've looked at. The other 30k lines of GUI or sorting, or options of writing PDF reports... blah, it might not be interesting to you... unless you're a font and layout geek and the reports did something interesting with fonts and/or layouts. Then you might only read that part.

Likewise, if it crashes you'll pull it up in the debugger and read parts of the functions on the stack that lead to the crash. Aha! The contract called for the caller to not pass any NULL pointers, and they passed one. Fix. Commit. You had a *reason* for reading that code.

Knuth disagrees (4, Interesting)

phantomfive (622387) | about 3 months ago | (#46028873)

Knuth disagrees, which is why he created Literate Programming [wikipedia.org] . If you aren't familiar with it, you should make yourself familiar. He suggests eventually someone might win a prize for literature from their code.

If you haven't seen it, you should check it out. His code has a table of contents, and could definitely be considered literature. His Tex code is so well organized, that you can find what you are looking for within 15 minutes, even if you're not really familiar with it. That's how code should be: written so other people can read it.

That's not what the author is talking about, though. He's talking about crappy code that wasn't written in a way that was easy to understand (I read the article; this is my understanding of it). So yeah, crappy code is not literature, or easy to 'decode.' Tautological.

A better analogy (1)

shilly (142940) | about 3 months ago | (#46028877)

Sounds like he needs to read "The Chosen" by Chaim Potok, where he'd find another analogy. Then he could try the chevruta model.

Code isn't literature (0)

Anonymous Coward | about 3 months ago | (#46028919)

Most of the code I see is spaghetti!

Its all mathematics. (0)

Anonymous Coward | about 3 months ago | (#46028951)

Reading a program is more like reading a mathematical proof.

It shows what the author understood as the problem, and the approach to a solution.

Thus it is much more like a "peer review" of a mathematical proof prior publication.

Other people's code? I can't even figure out mine! (4, Funny)

digitalhermit (113459) | about 3 months ago | (#46028993)

Perl jokes aside, I have some old code written in everything from bash to C to R to Java. The common theme among these absolutely stunning pieces of literature is how incomprehensible some of it can be just a few months later. Sure, good code is self documenting, good code reads like a sentence, a proper module fits on one page of screen (I have a 24" display with better than 1920x1080 resolution, btw) but if my code were indeed prose, it would cause eyes to bleed, to hemorrhage, to explode in a fantastic fountain of blood and aqueous fluid.

Sometimes I wrote bits of code without knowing that there were easier ways. I may do a "for item in $(ls *.csv)" instead of the proper "for item in *.csv" or some furious hackery to manually rotate 20x10 matrix into a 10x20 (single command in several languages), or try to parse an XML file by regex'ing and other madness... Sometimes I was drunk. There was one class where the instructor didn't like "showoffs" so code had to be written using only the commands that were covered in the lecture. The resulting code from that class was horrid. One of my earliest bits of code from the 80s sent escape sequences to a printer and there are several strings with non-ASCII characters. There is no way to understand the code without knowing the printer. I have similar code for an Atari that stored music in a BASIC string. That might be possible to decode only if one understood how the Atari made sound.

So this is why I can't get Outline View? (1)

Tsu Dho Nimh (663417) | about 3 months ago | (#46029001)

This may explain why the incredibly ancient feature request for an "Outline View" in OpenOffice has gone over a decade (Reported: 2002-04-10) with no resolution.

https://issues.apache.org/ooo/... [apache.org]

The mental mapping of code for programmers and the mental mapping of text to those of us who write literature and non-fiction is totally different. They can't visualize how an outline and headings and the cues fonts give readers differs from all the "mind maps", "document navigators", and other inadequate replacements they keep suggesting will fill the need.

We don't read poetry... (2)

j33px0r (722130) | about 3 months ago | (#46029211)

We don't read poetry, we decode it. Or maybe you would say that we interpret it? Depends upon your point of view. We don't read the original article, we skim it.

The original author is romanticizing the term literature, not that there is anything wrong with that of course, but literature is a term applied to everything from Dostoevsky to instructions for assembling a toy. Beautifully/Dreadfully written code could be labeled as art, poetry, literature, garbage, puzzling, cryptography, and a whole variety of other terms.

With all that being said and putting aside that I do not agree with the original author's definition of literature, I do appreciate their perspective.

Load More Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Sign up for Slashdot Newsletters
Create a Slashdot Account

Loading...