13 ms·
Programming Idioms
- BucketSort 7y agoReminds me of http://www.rosettacode.org/wiki/Rosetta_Code http://www.rosettacode.org/wiki/Rosetta_Code
- phoe-krk 7y agoThis seems to have the same function and purpose as Rosetta Code, although styled somewhat differently.
- aloisdg 7y ago"Please don't reinvent the wheel"
- mighty_bander 7y agoYeah, "Don't reinvent the wheel" is a ballsy statement for a site that poorly replicates existing work.
- chii 7y agoyou 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.
- mrmonkeyman 7y agoWe do have a lot of different wheels to be honest.
- JackFr 7y agoThe 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)
- jodrellblank 7y agohttps://aplcart.info/ https://aplcart.info/ for APL idioms
- tgv 7y agoBut concentrated on the simpler tasks. Rosetta Code has examples for Gaussian Elimination, but no string to number conversion. It also has some really esoteric languages. It's really more of a Rosetta Stone, while Programming Idioms is more of a lookup for the typical but infrequent stuff you (well, I) tend to forget when working in multiple languages.
- markild 7y agoCool 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).
- jessedhillon 7y agoisoformat() formats date objects into dates of ISO-8601 format (YYYY-mm-dd). It formats datetimes into something extra.
- dwringer 7y agoWhen 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-mm-dd/1429/python https://www.programming-idioms.org/idiom/99/format-date-yyyy... [2] https://docs.python.org/3/library/datetime.html#datetime.date.isoformat https://docs.python.org/3/library/datetime.html#datetime.dat...
- i_cant_speel 7y agoIt sounds like the person you responded to corrected it themselves.
- perfunctory 7y ago> "which _might_ produce something else" (it depends on the resolution of info in the date object). I am not sure what you mean by "the resolution of info in the date object". Can you clarify?
- 7y ago
- trampoliner 7y agoWould be great for the hoards of "self taught" programmers out there, who bluntly refuse to understand patterns (design or programming).
- mumblemumble 7y agoI'd say it's great for anyone. I'm classically trained, but a decades-old university education doesn't enable me to just magically know the idiomatic way to do X in a language that was created after I graduated. My real question would be, what does this do that Google's Stack Overflow hits don't do. One would hope that the answer is, "Give me advice on how to do it in Python 3.6 that didn't get downvoted to death because there's already a SO question on how to do it in Python 2.7." But the cynic in me knows that, in software, particularly software's social environment, the only effective way to clear out the old, obsolete, broken wheels so they're not always in the way is by re-inventing them.
- pacaro 7y agoHey! 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 7y agoResemble? Or resent?
- pacaro 7y agoIf 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
- self_awareness 7y agoThis 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.
- jdmichal 7y agoThe problem with this is that best can change over time as languages evolve. For instance, formatting a date in Java: https://www.programming-idioms.org/idiom/99/format-date-yyyy-mm-dd/1112/java https://www.programming-idioms.org/idiom/99/format-date-yyyy... The first listing was using a `SimpleDateFormat`, which for a long time really was the best way to do this. But now I would never recommend that over `String.format`, especially with the potential threading problems in the former. But the latter was not available until Java 1.5.
- skellera 7y agoAnd that’s fine. It would get voted down when it was no longer the best case.
- jdmichal 7y agoRealistically it would just sit there. At least that's what places like StackOverflow evidence. Meaning that whatever momentum it built up over the potential years of being the "right" answer would need to be overcome. Downvotes are typically reserved for wrong, not merely suboptimal. Especially since optimal and thereby suboptimal can change based on circumstance.
- Timpy 7y agoLet users contribute idioms, or request idioms for their language and use case... and we've reinvented the StackOverflow wheel
- wruza 7y agoI 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.
- Tade0 7y agoI applaud the effort, but some examples (in JS at least) appear to be outdated.
- mfoy_ 7y agoOr, alternatively, not ideal. For example: https://www.programming-idioms.org/idiom/174/make-http-post-request https://www.programming-idioms.org/idiom/174/make-http-post-... On Fetch: https://gomakethings.com/why-i-still-use-xhr-instead-of-the-fetch-api/ https://gomakethings.com/why-i-still-use-xhr-instead-of-the-...
- mikewhy 7y agoThat'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> }
- programminggeek 7y agoReinventing 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 7y ago"Don't use your reinvented wheel in production. Unless you invent like, git."
- deleted 7y ago[deleted]
- krapp 7y agoThe 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."
- addictedcs 7y agoFirst 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-randomness https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomnes...
- scottfr 7y agoThere are also issues with the JS examples. For example: """ Remove all occurrences of string w from string s1, and store the result in s2. var s2 = s1.replace(w, ''); """ Since w is a string, this will only replace the first occurrence, not all occurrences.
- wvenable 7y agoI may have been using JavaScript's replace method wrong my entire life...
- calibas 7y agoI changed it to: var regex = RegExp(w, 'g'); var s2 = s1.replace(regex, '');
- minitech 7y agoNow it doesn’t work if the string you want to replace has any regex special characters. One JS idiom for replace-all is str.split(before).join(after)
- scottfr 7y agoThat's also problematic. If w includes characters that have special meaning in a regex (e.g. a period), this will cause issues. You could try to escape those special characters but that is potentially error prone. For an arbitrary w, one approach is something kind of awful like: let s2 = s1; while (s2.includes(w)) { s2 = s2.replace(w, '') } Edit: minitech's solution is better.
- coldtea 7y agoIf 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 7y agoPeople who should have reinvented the wheel but didn't end up with legacy code and still maintain mainframes.
- coldtea 7y agoWell, 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...
- velox_io 7y agoRe-inventing the wheel is a funny idiom itself. In 99.9% of cases it holds true, it's easier/ cheaper to use existing/ off-the-shelf solutions. The other 0.1% (not absolute numbers), it makes sense to innovate. Quite a few idioms fall into this category, like premature optimisation being the route of all evil. You really don't want to be on either end of the scale. I don't think the website is redundant. Something I think is useful to be able to compare languages, especially when using a new language. Plus, languages are interesting, they're not just a syntax, they often bring a different way of thinking. One issue with the website is that there is no indication of example quality. For instance, the B-Tree* in C# has some issues[0]. Using classes instead of structs is horrible for memory management and garbage collection. As does not constrain the generic type to structs ("where T : struct"), this continues on from the above. None of this would be apparent unless you understand .Net's memory management, inheritance, garbage collection, and spent some time with generics. Many of the other languages have got this right. [0]https://www.programming-idioms.org/idiom/9/create-a-binary-tree-data-structure#impl1554 https://www.programming-idioms.org/idiom/9/create-a-binary-t... *I have often wondered why trees aren't standard collections, inserting nodes and tree rotations etc are common use cases for B-Trees. This does feel like re-inventing the wheel, giving developers plenty of opportunity to screw things up. Tries are another structure I think they have left out, there are times when tries are often a better solution than dictionaries (urls spring to mind).
- dahart 7y agoDo 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 7y agoI 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 7y agoSorry 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 7y agoPython 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.
- ukj 7y agoThe 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.
- chucksmash 7y agoThe flip side of the naming-things-is-hard adage in programming is that once you can name the problem you are having, the problem often evaporates before your eyes.
- ukj 7y agoDefining the problem is half the solution ;)
- kozziollek 7y agoThat'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 7y agohoogle 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"
- zwieback 7y agoThis is a problem in general but especially in programming where people like to rename things that already exist. However, it's not exclusive to programming - when I hack my way through something ME or EE I ask the experts around me and they can usually tell me the proper name or point me to existing or very similar solutions.
- seamyb88 7y ago#include <wheel.h>
- deleted 7y ago[deleted]
- tomp 7y agoHm... 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 7y agoYour solution only works if it's the end of the program. Sometimes you need to exit conditionally. if foo: exit(0) more_code()
- tomp 7y agoIMO that's anti-pattern / code smell, in most situations.
- ainiriand 7y agoYou are right, as for example the tests would behave in an erratic way. It should be allowed to complete.
- aepiepaey 7y agoAs long as we're talking about libraries, yes. For cli tools, on the other hand, there are definitely legitimate cases for exiting early.
- tomp 7y agoSure, 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...
- kbenson 7y agoWell, 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.
- grumpy8 7y agoI'd look into "webdesign-idioms"
- s9w 7y agoIt's certainly very retro looking
- thsealienbstrds 7y agoQuality 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>.
- svnpenn 7y agoI run a similar site: https://cup.github.io/autumn https://cup.github.io/autumn
- tmsh 7y agosubstring for c++ and other languages needs an j-i+1.
- velcrovan 7y agoHey, 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!
- c3534l 7y agoThese 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.
- SamBam 7y agoYou're correct, and I think "patterns" would be a more straightforward term. I believe the confusion probably stems from the word "idiomatic," which means "using, containing, or denoting expressions that are natural to a native speaker." i.e. "idiomatic English" simply means that it sounds like a native speaker. Likewise, "idiomatic python" would be code that reads like a fluent python programmer.
- afiori 7y agoand to sum it up the "if __name__ == "__main__":" is a standard idiomatic pattern in python
- Dylan16807 7y ago"Idiom" and "idiomatic" are connected. You've just demonstrated that the use is correct.
- SamBam 7y agoOf course they are "connected." I was explaining the confusion. However, "connected" is not the same as meaning the same thing. 1. idiom: a group of words established by usage as having a meaning not deducible from those of the individual words (e.g., rain cats and dogs, see the light ). 2. idiomatic: using, containing, or denoting expressions that are natural to a native speaker. Also "connected" is "idiosyncratic," and that means yet a third thing. "Idiosyncratic programming" would be the opposite of what you want! (Definitions from Oxford University Press / https://www.lexico.com/en https://www.lexico.com/en)
- nmca 7y agoThe first one I saw was wrong, suggesting map over list comprehension in python...
- dagurp 7y agoIf you're using Python 3 then map should be fine
- suixo 7y agoI 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 7y agoYeah, integers can't overflow. It will just use all of your memory. Unless you're using a C bind, like numpy.
- hota_mazi 7y agoMore recipes than idioms.
- inlined 7y agoIt 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.
- stOneskull 7y agoi 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.
- treeform 7y agoI was going to fill in the nim stuff, but: Sorry, [nim] is currently not a supported language.
- simplyconnected 7y agoBeen wanting this for a while. How else can one communicate the power of ciso8601 over step time?
- yellowapple 7y agoThe 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.
- blobs 7y agoThe 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.
- banachtarski 7y agoI 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).
- kerkeslager 7y agoI'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
- m463 7y agoI love rosetta code! I do agree it needs improvement. It would be nice if it had an interface to browse and do a:b comparisons in a more fluid manner. The programming idioms site does this well.
- ravenstine 7y ago> 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!
- kerkeslager 7y agoDid you really just quote two words, "better content", out of context? Please go back and answer the question "Better content than what?" before assuming you know what's debatable. > Way to overcomplicate FizzBuzz! So write a simpler one and post it. It's a Wiki.
- ravenstine 7y agoAnybody reasonable person reading my comment would know what I'm talking about; the context is directly above it. Using your proposed logic, quoting "Rosetta Code has more content and better content" wouldn't have been enough because it's missing context. There's no need to be fussy about this. > So write a simpler one and post it. It's a Wiki. It's my prerogative to criticize other people's content. Simultaneously, I'm under no obligation to write content on someone else's website for free.
- stellalo 7y agoIt’s funny how the most empty row in the coverage table is “matrix multiplication” — only the FORTRAN implementation is there
- alkonaut 7y agoI 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.
- cr0sh 7y agoIf 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.
- varjag 7y agohttps://www.programming-idioms.org/idiom/117/get-list-size/1996/c https://www.programming-idioms.org/idiom/117/get-list-size/1... lol
- arcticwombat 7y agoEh, what's wrong with Rosetta Code? A metric ton of examples in a metric ton of languages. What's better about this one?
- mettamage 7y agoThis is a great place to see if I have conceptual knowledge gap. Which is why I am asking: where are the metaprogramming idioms?
- tabtab 7y agoFancy 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.
- val_deleplace 7y agoThis 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-hacker-news-my-dreaded-google-cloud-invoice-6b940dd9eba6 https://medium.com/google-cloud/surviving-traffic-spike-from...