gdritter repos documents / master posts / idiomaticity.md
master

Tree @master (Download .tar.gz)

idiomaticity.md @master

01dddef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
## 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:

~~~.python
for x in range(10):
    foo(x)
~~~

We could, of course, write an effectively identical loop using the
`while` function:

~~~.python
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:

~~~.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: 

## Idiomatic and Non-Idiomatic Systems