Tree @master (Download .tar.gz)
- ..
- 2014-02-03
- 4d-chess.md
- a-small-haskell-record-complaint
- cherenkov.md
- codata
- commonplace
- daemontools.html
- daemontools.md
- data-files-and-backpack.md
- distributed-git.md
- file-system
- formats.md
- higher-rank-trait-bounds.md
- idiomaticity.md
- in-defense-of-hm
- madlibs-intro.md
- madlibs-ml.md
- madlibs-scheme.md
- multiwhile.md
- orwell.md
- resources-laziness-and-cps.md
- script-based-data-analysis
- semigroup.html
- semigroup.md
- sexprs.md
- shift-resolve-parsing.md
- some-rust-errors.md
- static-versus-dyn
- tansu
- tc-post.md
- tc-post.md.bak
- telml.md
- typeclasses.md
- writer-leak.md
idiomaticity.md @master — view markup · raw · history · blame
Idiomatic and Non-Idiomatic Code
You'll come across a lot of discussions about some bit of code in
some language being "idiomatic" or "non-idiomatic". The meaning of
this is reasonably clear: it means existing code in that language
will do things in a similar way. As a trivial example: looping over
a range of numbers in Python is usually done with for
loops and
the range
function:
for x in range(10):
foo(x)
We could, of course, write an effectively identical loop using the
while
function:
x = 0
while x < 10:
foo(x)
x += 1
But in this case, the code in question is much less idiomatic, and for very good reasons: it's more complicated, longer, and easier to screw up (e.g. by forgetting a line or getting a token wrong.) On the other hand, the following is safer and clearer than a while loop, and we'd still consider it unidiomatic Python:
IntRange(0, 10).each(foo)
The above code (assuming we've implemented IntRange
) is pretty
clear and doesn't suffer from the safety problems of the while
-based
code, but it's still not idiomatic. We can conclude that being
"idiomatic" isn't just about clarity or convenience or safety: it
instead has to do with conforming to technical and social choices
within an existing system.
That raises the question: if we can write code that's safe and clear and concise but still not idiomatic, then what does writing "idiomatic code" buy us?
Why Be Idiomatic?
There's a strong social advantage to writing idiomatic code: other people are used to reading idiomatic code, so your audience will find your code clearer and easier to read and, above all, less surprising.
But there are strong technical advantages, too: