| 1 |
## Idiomatic and Non-Idiomatic Code
|
| 2 |
|
| 3 |
You'll come across a lot of discussions about some bit of code in
|
| 4 |
some language being "idiomatic" or "non-idiomatic". The meaning of
|
| 5 |
this is reasonably clear: it means existing code in that language
|
| 6 |
will do things in a similar way. As a trivial example: looping over
|
| 7 |
a range of numbers in Python is usually done with `for` loops and
|
| 8 |
the `range` function:
|
| 9 |
|
| 10 |
~~~.python
|
| 11 |
for x in range(10):
|
| 12 |
foo(x)
|
| 13 |
~~~
|
| 14 |
|
| 15 |
We could, of course, write an effectively identical loop using the
|
| 16 |
`while` function:
|
| 17 |
|
| 18 |
~~~.python
|
| 19 |
x = 0
|
| 20 |
while x < 10:
|
| 21 |
foo(x)
|
| 22 |
x += 1
|
| 23 |
~~~
|
| 24 |
|
| 25 |
But in this case, the code in question is much less idiomatic, and
|
| 26 |
for very good reasons: it's more complicated, longer, and easier
|
| 27 |
to screw up (e.g. by forgetting a line or getting a token wrong.)
|
| 28 |
On the other hand, the following is safer and clearer than a
|
| 29 |
while loop, and we'd _still_ consider it unidiomatic Python:
|
| 30 |
|
| 31 |
~~~.python
|
| 32 |
IntRange(0, 10).each(foo)
|
| 33 |
~~~
|
| 34 |
|
| 35 |
The above code (assuming we've implemented `IntRange`) is pretty
|
| 36 |
clear and doesn't suffer from the safety problems of the `while`-based
|
| 37 |
code, but it's still not idiomatic. We can conclude that being
|
| 38 |
"idiomatic" isn't just about clarity or convenience or safety: it
|
| 39 |
instead has to do with conforming to technical and social choices
|
| 40 |
within an existing system.
|
| 41 |
|
| 42 |
That raises the question: if we can write code that's safe and clear
|
| 43 |
and concise but still not idiomatic, then what does writing "idiomatic
|
| 44 |
code" buy us?
|
| 45 |
|
| 46 |
## Why Be Idiomatic?
|
| 47 |
|
| 48 |
There's a strong social advantage to writing idiomatic code: other
|
| 49 |
people are used to reading idiomatic code, so your audience will find
|
| 50 |
your code clearer and easier to read and, above all, _less surprising_.
|
| 51 |
|
| 52 |
But there are strong technical advantages, too:
|
| 53 |
|
| 54 |
## Idiomatic and Non-Idiomatic Systems
|