
Programming Idioms - hazbo
https://www.programming-idioms.org
======
c3534l
These really aren't idioms. An idiom in natural language is a phrase or saying
whose meaning cannot be understood without someone telling you what it's
supposed to mean (that is, you can't figure it out just by reading the words).

In programming, an idiom is a common, accepted way of accomplishing a task
which you wouldn't figure out to do all on your own and whose meaning isn't
obvious to programmers of other languages.

I suppose you could argue that certain idioms are more or less universal:
using "i" as the index in a loop isn't obvious even if you know a lot of math
(why not use j?).

But no one who doesn't program Python is going to figure out the first thing
you do in any new Python project is write the line:

    
    
        if __name__ == "__main__":
            main()
    
    

The fact that it's impenetrable if it's not first explained to you that you
should do that is what makes it idiomatic.

Idiomatic also means particular to a specific person or group. If your website
is based on comparing the same idiom in multiple languages, that's a good
indication it's not actually idiomatic. That's probably just a common task.

~~~
geoelectric
I think you captured definitions really well, but I'm not sure you captured
the spirit of a programming idiom.

The spirit is essentially pattern-like, that the specific syntax has a higher
meaning in that language such that as soon as you see its shape you know
what's up. Moreover, if you don't see that shape it doesn't register as
"native" for that language.

In your explanation, the spirit is "entry point is main." It's true the
mechanics are unusual to Python, but that's not necessary and not all that
counts. If I did the name/main comparison some other way it wouldn't be
idiomatic because that very specific construct is the idiom.

Some examples in other languages that aren't that hard to read mechanically:

    
    
        param = param || default; // idiomatic for ES5 default
    
        let bool = !!(whatever) // idiomatic for boolean coercion in JS
    
        reversed_list = forward_list[::-1] # idiomatic for sequence reversal in Python
    
        x = x >> 1 // idiomatic for x/2 in C
    

In some of those cases there are practical realities that also drive them (the
bitshift divide in particular comes from embedded and other speed concerns)
but they aren't constructs that you see elsewhere very much outside that
language even if they're valid. That's what makes them idiomatic to that
language.

~~~
saagarjha
> the bitshift divide in particular comes from embedded and other speed
> concerns

Please don't do this unless you are using a really bad toolchain: most
compilers will optimize x /= 2 for you.

~~~
voltagex_
[https://godbolt.org/z/nwk0Jm](https://godbolt.org/z/nwk0Jm) and
[https://godbolt.org/z/bGcD4Y](https://godbolt.org/z/bGcD4Y) show some
differences - someone much better at assembly will have to explain this one.

~~~
klipt
[https://www.geeksforgeeks.org/left-shift-right-shift-
operato...](https://www.geeksforgeeks.org/left-shift-right-shift-operators-c-
cpp/)

"The left shift and right shift operators should not be used for negative
numbers. The result of is undefined behaviour if any of the operands is a
negative number."

Might be one reason?

------
addictedcs
First example I've checked is wrong [1]. Shuffle a list, with a static Random
object initialization. Using a static random object is not thread-safe in
.NET.

"One common solution is to use a static field to store a single instance of
Random and reuse it. That’s okay in Java (where Random is thread-safe) but
it’s not so good in .NET – if you use the same instance repeatedly from .NET,
you can corrupt the internal data structures." [2]

Very often the very same resources which claim to be the source of truth
provide bad code examples.

[1] [https://www.programming-
idioms.org/cheatsheet/Csharp](https://www.programming-
idioms.org/cheatsheet/Csharp)

[2] [https://codeblog.jonskeet.uk/2009/11/04/revisiting-
randomnes...](https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness)

~~~
Tharre
Quite frankly, this site's examples are pretty horrible.

Case in point, Idiom #46 in C[0] uses strncpy and predictably fails to
correctly terminate the buffer.

Idiom #55[1] converts a integer to a string with itoa, never bothering to
mention that it isn't part of the C standard or POSIX, while for some reason
using a 4096 byte big output buffer.

Idiom #39[2] first example uses clrscr(), which I assume is some sort of old
DOS function? The entire example looks unrelated to the problem.

The idea is certainly good, but you need some serious vetting system to make
this usable.

[0] [https://www.programming-
idioms.org/idiom/46/impl/477](https://www.programming-
idioms.org/idiom/46/impl/477)

[1] [https://www.programming-
idioms.org/idiom/55/impl/438](https://www.programming-
idioms.org/idiom/55/impl/438)

[2] [https://www.programming-
idioms.org/idiom/39/impl/2042](https://www.programming-
idioms.org/idiom/39/impl/2042)

~~~
wruza
%d for strlen is cute as well.

That’s the fate of all such sites. They start with a nice idea and a good
intent, but the crowd fills it with crap, nobody cares/is able to screen it,
and it instantly becomes an unreliable source of nonsense.

Ed: btw, #1 is terminated by calloc(6), but it is indeed a trip mine looking
for prey. It is unknown if strncpy was used intentionally or out of ignorance
and if the next person will be aware.

~~~
5-
> #1 is terminated by calloc(6)

Yet this seems to be the perfect place and time to remind the kind audience
that sizeof measures the number of char-sized chunks, thus sizeof(char) is
always the constant 1, no need to spell it out.

------
kerkeslager
I'd like to draw people's attention away from this and to Rosetta Code[1].

Programming Idioms has a slightly more modern interface, but what matters more
is the content. Rosetta Code has _more_ content and _better_ content. If you
don't like Rosetta Code's interface, I'd rather you tried to improve Rosetta
Code rather than splintering the already-small community of people producing
this sort of content.

[1]
[https://rosettacode.org/wiki/Rosetta_Code](https://rosettacode.org/wiki/Rosetta_Code)

~~~
ravenstine
> better content

That's debatable. I suppose it's better than nothing for complete noobs, but a
lot of the examples on that site are even worse than the crap found on Stack
Overflow.

Take this for example:
[http://rosettacode.org/wiki/FizzBuzz#ES6](http://rosettacode.org/wiki/FizzBuzz#ES6)

Way to overcomplicate FizzBuzz!

------
markild
Cool project.

I'm a bit reluctant to trust the quality of this, however.

The first example I looked up was "Format date YYYY-MM-DD" in Python, which
wanted me to use "isoformat()", which produces something else.

It was easy to correct, but I'd like to see a more "democratic" approach to
getting correct examples, not just taking the latest one as fact.

edit: Sorry, more precise critique of the usage of "isoformat" would be "which
_might_ produce something else" (it depends on the resolution of info in the
date object).

~~~
dwringer
When I view that page[1] I see two different techniques listed, isoformat()
being the second. The first is to use d.strftime('%Y-%m-%d').

In regard to the second, isoformat on a "datetime" will give increased
resolution beyond "YYYY-MM-DD", but a "date" object only resolves year, month
and day and such a call will indeed yield the correct output (per the linked
documentation at [2]).

[1] [https://www.programming-idioms.org/idiom/99/format-date-
yyyy...](https://www.programming-idioms.org/idiom/99/format-date-yyyy-mm-
dd/1429/python)

[2]
[https://docs.python.org/3/library/datetime.html#datetime.dat...](https://docs.python.org/3/library/datetime.html#datetime.date.isoformat)

~~~
i_cant_speel
It sounds like the person you responded to corrected it themselves.

------
tomp
Hm... _Idiom #186 Exit program cleanly_ for _Python_ :

    
    
      import sys
      sys.exit(0)
    

Well, I guess I've been reinventing the wheel for my whole career... and thank
god I did, my wheel is not only more performant, but also shorter and produces
cleaner code (in my subjective opinion). As simple as:

    
    
      # nothing

~~~
lkbm
Your solution only works if it's the end of the program. Sometimes you need to
exit conditionally.

    
    
      if foo:
          exit(0)
      more_code()

~~~
tomp
IMO that's anti-pattern / code smell, in most situations.

~~~
aepiepaey
As long as we're talking about libraries, yes.

For cli tools, on the other hand, there are definitely legitimate cases for
exiting early.

~~~
tomp
Sure, but even in most of those scenarios, I’d prefer to structure the code
differently... perhaps write a _main()_ function that just returns, or other
functions... more modular, maintainable, teatable, ... admittedly, in Python
you _need_ to use _os.exit_ if you want to return a specific non-zero exit
code, but even in that case good code style would be something like

    
    
      def main()
        blablabla
        if foo:
          return bar
        ...
        return 8
      
      if __name__ == “__main__”:
        os.exit(main())
    

Of course that’s just my advice / opinion / preference, other ways are valid
as well...

------
coldtea
If people didn't re-invent the wheel we'd still be using wheels made of rock
like the Flintstones (or at best wooden wheel, like 4 millennia ago).

~~~
seamyb88
People who should have reinvented the wheel but didn't end up with legacy code
and still maintain mainframes.

~~~
coldtea
Well, people who should have reinvented the wheel, ended up stuck with legacy
dependencies they've used instead, in various states of abandonment and
disintegration now, who do 200 other things besides the wheel function they
just needed, and which nobody can understand and are a pain to maintain and
frequently break things on updates.

Now they wish they had taken the time to just write their ten lines wheel
themselves...

It's almost as if there's a balance...

------
ukj
The reason I re-invent wheels is because I don't know the idiom I need to
Google for.

I know what I need. I don't know what it's called in English. It's faster to
re-implement it than to learn the vocabulary.

~~~
kozziollek
That's why Haskell's Hoogle [1] is amazing (at least during 7-week course at
university). You type function signature and get already implemented
functions.

[1] [https://hoogle.haskell.org/](https://hoogle.haskell.org/)

~~~
uryga
hoogle is great, but it gives you library functions. it won't teach you
higher-level patterns like

    
    
      f <$> x <*> y <*> z
    

to "map a function over three values"

------
yellowapple
The C implementation (and probably most of the other implementations) of Idiom
#41 (reverse a string) doesn't correctly handle UTF-8; it just reverses an
array of bytes. Normally I wouldn't take objection to this, but:

1) The problem description specifies "Each character must be handled correctly
regardless its number of bytes in memory.", for which the C implementation
rather plainly fails.

2) UTF-8 is so ubiquitous nowadays that any string-manipulating function that
fails to correctly handle multibyte UTF-8 characters ought to be considered
broken.

------
suixo
I love the "check if integer addition will overflow" in Python:

def adding_will_overflow(x, y): return False

I have no idea if it's actually true but I find that funny.

~~~
ORioN63
Yeah, integers can't overflow. It will just use all of your memory.

Unless you're using a C bind, like numpy.

------
dahart
Do these count as “idioms”? Are these problems commonly messed up? I sampled a
dozen or so and all the ones I saw are snippets for doing really basic tasks,
but didn’t seem particularly idiomatic, nor like tasks that cause a lot of
bugs...

~~~
chrisseaton
I don’t know what you understand an ‘idiom’ is, but being commonly
misunderstood or a common source of errors is nothing to do with being an
idiom. I don’t know how getting the size of an array could _not_ be idiomatic.

~~~
dahart
Sorry I wasn't clear. I was responding to two different claims made in the
title of this site: first that the samples are "idioms", and second that
people should avoid reinventing the wheel in production code. It's not clear
to me how these samples accomplish either.

"Idiom" means something that is done in a characteristic style. For example,
in Python, it's idiomatic to use list comprehensions rather than for loops.

I don't see how getting the size of an array could be idiomatic in that sense,
because there is always only a single way to do it, it's never a stylistic
choice.

~~~
vharuck
Python certainly makes some of the tasks so simple as to be moot. But some
people try to bend a new language to match what they're used to.

For example, R is a statistical programming language where almost all data
structures and operations are for vectors or arrays. But it's not unusual to
see people on StackOverflow or blogs reinventing wheels like map/reduce/filter
with for loops. I agree it's just inexperience that led to it, but the
"intended" way is still idiomatic.

------
cr0sh
If you're going to list Fortran, COBOL, Prolog, Ada, Lisp, etc - I'm of the
opinion that you need to list BASIC as well.

You list VB - but you don't say if this is VB.NET, or prior VB versions
(3,4,5,6)? VB.NET isn't quite identical to the others...

...and VB is nothing like plain-old BASIC (and later dialects). In fact, you
might lump them all under BASIC, as VB owes more to BASIC than being it's own
thing (though VB.NET seems more a name than being BASIC - just my opinion,
though, as a long time ago VB3-6 coder - I'd call it "BASIC-ish").

Other than that - this looks interesting. UI could use a bit more work, but
seems like a good start.

------
thsealienbstrds
Quality of the site aside, this concept would be great with JSON-API or
something so it can be integrated with <insert favorite editor/IDE here>.

------
velcrovan
Hey, it's a neat project. Of course it could use improvements and a few
disclaimers, but hey. Good on you for making it.

Added a request for Racket support!

------
krapp
The wheel is, in terms of elegance and function, a perfect machine - it can't
be simplified, nor can it be improved upon. The point of the idiom being that
any attempt to do so will either lead back to the wheel, or an inferior,
unnecessarily complex alternative.

The problem with applying this to programming is the implication that there
are languages, frameworks, patterns, and idioms which are equivalent to the
wheel, in that there always exists one objectively correct, perfect solution
which can't be improved upon. I don't believe programming has the equivalent
of a wheel, yet.

What people tend to mean when they say "don't reinvent the wheel" in the
context of programming is either "don't waste time writing code that already
exists and is _adequate_ " or "don't use $X because I like $Y."

------
alkonaut
I think what happens with this is too much context is lost and in the end you
can't really describe what the "right way" to do things is.

Is the right way to delete a file

    
    
       result = os.deletefile(path)
    

or is it

    
    
       try { os.deletefile(path) } catch (ex) { log(ex) } 
    

and what is the difference? Both may be valid and idiomatic _in the same
language_. With more context such as a forum dialog or a StackOverflow
question, these things are usually ironed out. But trying to do the same thing
in Haskell (where you might have monadic error handling) or java (where you
might have some exception handling chain) is very different even though the
same function call is used in the end to actually delete a file.

------
grumpy8
I'd look into "webdesign-idioms"

~~~
s9w
It's certainly very retro looking

------
inlined
It seems like the checklist blurs the lines between a language and standard
libraries, something that shouldn’t be controversial but should be noted.

The checklist also seems to favor dynamic languages. E.g. does Go deserve to
miss a checkmark because you can’t determine if a variable exists at runtime
(only at compile time)? I can sorta see the source inclusion checkbox, but
it’s not entirely clear from the example if this is testing for a macro
support, AOP, or dynamic loading of libraries.

------
blobs
The idea is great. But the low quality of many code examples puts me off. For
me it would only work if the examples shown are made by a selection of top
level developers. Then it would be really nice actually.

About the site design, the little menu on the left should better not move the
content window to the right. Now, when you scroll down in 'all idioms' for
example, the list is right aligned and left has useless whitespace. A
horizontal menu or dropdown would be better I guess.

------
val_deleplace
This submission being popular in HN caused an interesting traffic spike in
Programming Idioms. Here is a detailed recital of the technical and financial
consequences: [https://medium.com/google-cloud/surviving-traffic-spike-
from...](https://medium.com/google-cloud/surviving-traffic-spike-from-hacker-
news-my-dreaded-google-cloud-invoice-6b940dd9eba6)

------
self_awareness
This site would really gain by having an upvote mechanism, this way users
would know what is the "best" way of doing things. Plus, needs more languages.

~~~
Timpy
Let users contribute idioms, or request idioms for their language and use
case... and we've reinvented the StackOverflow wheel

~~~
wruza
I don’t know what the exact process is, but one can simply create something
like
[https://codesnippet.stackexchange.com](https://codesnippet.stackexchange.com)
and benefit from the established network.

------
banachtarski
I took a gander at a bunch of the C++ ones. They are pretty horrible. It looks
like direct translations from generic snippets (just a syntax transformation).

------
svnpenn
I run a similar site:

[https://cup.github.io/autumn](https://cup.github.io/autumn)

------
tabtab
Fancy data structure manipulation perhaps should be part of a library (API)
and not "built in" to the base language. The best languages make it easy to
use vast API's rather than hard-wire features into syntax.

------
nmca
The first one I saw was wrong, suggesting map over list comprehension in
python...

~~~
dagurp
If you're using Python 3 then map should be fine

------
Tade0
I applaud the effort, but some examples (in JS at least) appear to be
outdated.

~~~
mfoy_
Or, alternatively, not ideal. For example: [https://www.programming-
idioms.org/idiom/174/make-http-post-...](https://www.programming-
idioms.org/idiom/174/make-http-post-request)

On Fetch: [https://gomakethings.com/why-i-still-use-xhr-instead-of-
the-...](https://gomakethings.com/why-i-still-use-xhr-instead-of-the-fetch-
api/)

~~~
mikewhy
That's a whole lot of code / diatribe for what is:

    
    
        const _fetch = window.fetch
    
        /** Fetch overload that handles error status */
        export function fetch(input: RequestInfo, init?: RequestInit) {
          return _fetch(input, init).then(checkResponseCode)
        }
    
        function checkResponseCode(response: Response) {
          if (response.status >= 400) {
            const err = new Error(`Error ${response.status} from ${response.url}`) as any
            err.fetchHttpResponse = response
            throw err
          }
    
          return response
        }
    
        /** Convenience method */
        export function getJson<TJsonBody = any>(
          input: RequestInfo,
          init?: RequestInitJson,
        ) {
          return fetch(input, init).then((response) => response.json()) as Promise<TJsonBody>
        }

------
varjag
[https://www.programming-idioms.org/idiom/117/get-list-
size/1...](https://www.programming-idioms.org/idiom/117/get-list-size/1996/c)

lol

------
treeform
I was going to fill in the nim stuff, but:

Sorry, [nim] is currently not a supported language.

------
kbenson
Well, I knew it was only a matter of time before someone made this. This was
one of my favorite "some day I'll have time and can make this site" ideas.

------
mettamage
This is a great place to see if I have conceptual knowledge gap. Which is why
I am asking: where are the metaprogramming idioms?

------
stellalo
It’s funny how the most empty row in the coverage table is “matrix
multiplication” — only the FORTRAN implementation is there

------
arcticwombat
Eh, what's wrong with Rosetta Code? A metric ton of examples in a metric ton
of languages.

What's better about this one?

------
simplyconnected
Been wanting this for a while. How else can one communicate the power of
ciso8601 over step time?

------
hota_mazi
More recipes than idioms.

------
programminggeek
Reinventing the wheel is a good idea. It's how you learn. Programmers who say
"don't reinvent the wheel" don't understand how the craft of wheel making
works.

~~~
jacobush
"Don't use your reinvented wheel in production. Unless you invent like, git."

------
stOneskull
i like looking at how other languages do things. i'm pushed away from Go and
pulled toward Rust, the two languages i've been thinking of getting deep into.
like the currying example. that move keyword seems pretty nice.

------
tmsh
substring for c++ and other languages needs an j-i+1.

------
BucketSort
Reminds me of
[http://www.rosettacode.org/wiki/Rosetta_Code](http://www.rosettacode.org/wiki/Rosetta_Code)

~~~
mighty_bander
Yeah, "Don't reinvent the wheel" is a ballsy statement for a site that poorly
replicates existing work.

~~~
chii
you want to be known as the one who invented the wheel, because it looks good
as a resume item. That's why the wheel keeps getting reinvented again and
again, and usually quite poorly.

~~~
JackFr
The wheel gets reinvented because wheels are extremely useful, not because
they look good on resumes. (OTOH, Greenspun's tenth rule is a different story:
[https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule](https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule))

------
trampoliner
Would be great for the hoards of "self taught" programmers out there, who
bluntly refuse to understand patterns (design or programming).

~~~
pacaro
Hey! I'm a self taught programmer and I resemble that remark.

I think that you're painting with a little too broad a brush, the inverse is
true too, I've seen way too much blind application of GoF patterns by
_professional_ engineers.

I think the key word is _understanding_. what each idiom needs is a good
rubric explaining why this is the/a correct approach, but that is much harder
to provide

~~~
lewilewilewi
Resemble? Or resent?

~~~
pacaro
If you haven't encountered the phrase before, "I resemble that remark" is
absolutely a play on the similarity between resemble and resent, suggesting in
a light hearted fashion that the speaker has (perhaps) mild resentment, but
recognises the truth because it is personally applicable. It also has an
overtone (at least to me) of downplaying the seriousness of the "remark" by
answering it with humor

For myself I'm a 25 year industry veteran, with 35 years of self-taught
programming experience.

My experience with stereotypes and generalizations is that the problem is not
so much that they might be wrong, but rather that they are always incomplete

