285 points · by mkl95 · 5y ago · 98 comments
Add the ability for people to improve or debate the solutions. Ultimately we should have a large curated cookbook (with additional variant selections and associated recipe variants).
The most important human element of programming is knowing what to build (and what pieces to build to make the bigger thing). How often do I have to lookup ways to read a file in Ruby?... most times I need to read a file, I have to refer to the different approaches. I just don't do that often enough to remember everything. What I do know is, "this will be a lot of data, so I need to read it line by line or in chunks". That should be all you need to know, and then you pull up a recipe.
We have that, rosettacode.org .
For example IntoIterator wasn't defined for Rust arrays, and then one day Rust 1.54 implemented IntoIterator on arrays (and hacked things so that this doesn't cause old code to do something unexpected, Rust 2021 will remove that hack since old code wouldn't claim to be Rust 2021, thereby unlocking the new behaviour for syntax that once meant something different). Anyway this changes the idiomatic way to do various trivial array operations, since previously you'd have created a reference to the array, that has IntoIterator so that you can iterate it. That still works, but it's no longer idiomatic.
for &x in &[2, 4, 6, 8, 10] /* needed until 1.54 */
for x in [2, 4, 6, 8, 10] /* makes more sense */There's no "debate" capabilities, though.
Also: some people really oppose "var." I don't understand why, especially when newer languages like Swift and Rust really encourage similar idioms. Something something = new Something () is usually a smell to me. I personally find "var" much easier to work with.
From msdn/dotnet documentation:
> The use of var helps simplify your code, but its use should be restricted to cases where it is required, or when it makes your code easier to read.
https://docs.microsoft.com/en-us/dotnet/csharp/programming-g...
Also, C# 9.0 introduces target-typed new expressions:
https://docs.microsoft.com/en-us/dotnet/csharp/language-refe...
The argument that code becomes unreadable without an IDE is only true if identifiers aren't named properly (for example by heavy abuse of abbreviations, or even the usage of single-letter symbols).
The only places where type-inference should be avoided are "public interface" kind of things. It's best practice to be explicit about an "interface"—even in languages with full type inference. This avoids changing an interface unnoticed only by changing an expression somewhere. (I don't mean here C#'s Interfaces verbatim, but for example signatures of "package public" methods and such).
var x = new Foo()
C# should have fewer, better considered features imo. var something = new Something()
... this one in C# is probably using type inference? Or maybe it doesn't matter in C# because it has a dynamic type anyways? Yes, Rust permits type inference but sometimes it can't infer it and you have to specify it. And sometimes it's clearer to be explicit about the type. C++ permits it too (auto) but depending on the team it can be pretty unpopular except for maybe verbose type names/iterator types, etc.> Idiom #120 Read integer from stdin
> Read an integer value from the standard input into variable n
int n[15];
fgets(n, 15, stdin);
Really?> Idiom #137 Check if string contains only digits
> Set boolean b to true if string s contains only characters in range '0'..'9', false otherwise.
char b = 0;
for (int i = 0; i < strlen(s); i++) {
if (! (b = (s[i] >= '0' && s[i] <= '9'))) break;
}
I appreciate the funny assignment-and-test-and-early-break in one (although I'd hardly say it's idiomatic), but I could do without the quadratic strlen().Also, code like this should always be put inside a function that returns a value, not just written inline. Making it a function allows simpler and more understandable code too.
The funniest part is that it is not necessary to call strlen() at all! The whole thing can be written in a single pass over the string. Here is how I would code it in C:
int OnlyDigits( char str[] ) {
for( int i = 0; str[i] != '\0'; ++i ) {
if( str[i] < '0' || str[i] > '9' ) return 0;
}
return 1;
}
Try it here:What about adding a check of str[0] == 0 -> return 0 Also, giving char str[] will make it char* str. Which can be null. This may cause reading a random memory location (possibly segfault or use-after-free)
edit: I get the comments but empty string still contains no digits. Given the regex would be ^[0-9]+ (+ instead of *) What I want to say is string has a numerical value or not. Empty string is NaN.
It shows what happens if you take away the compilers' ability to reason about 's': it could be a global variable, and 'foo' could be modifying it, so now the compiler has to call strlen on every iteration.
So even though 'strlen' gets optimized out in the original version, it's quite a maintenance hazard since any minor change could inadvertently change the complexity from linear to quadratic. It also doesn't get optimized in debug builds, making those far slower than necessary.
int n = strspn(s,"0123456789");
BOOL b = (s[n] == 0);But that's the future of programing! Just ask Microsoft or JetBrains.
Soon, with the help of AI, any random dude will be empowered to write software!
Big layoffs are to be expected as AI will take over most of the high-paying jobs in the software industry.
Belief me. /s
- There are no standard integer types that take 15 (decimal) digits to represent.
- The array contains ints instead of chars
- Why would you use fgets() instead of just gets()? (Though I don't touch C very often so perhaps that is considered proper style)
- Obviously no conversion of the digits into else, let alone specifying a base or handling a `0x` prefix for hexadecimal or a minus sign for negative numbers.
I assume it's because gets() ranks as "-10: It's impossible to get right" on Rusty's API Design Manifesto? (http://sweng.the-davies.net/Home/rustys-api-design-manifesto)
Nitpick: that is irrelevant. The code reads in at most 14 characters.
> Why would you use fgets() instead of just gets()?
You don’t use gets because it doesn’t exist anymore. It got removed in C11 (it rightfully was deemed so bad that backwards compatibility was sacrificed). You can use
char *gets_s( char *str, rsize_t n )
, though. man gets
...
SECURITY CONSIDERATIONS
The gets() function cannot be used securely. Because of its lack of
bounds checking, and the inability for the calling program to reliably
determine the length of the next incoming line, the use of this function
enables malicious users to arbitrarily change a running program's func-
tionality through a buffer overflow attack. It is strongly suggested
that the fgets() function be used in all cases. (See the FSA.)https://programming-idioms.org/idiom/184/tomorrow
I’ve always found it interesting to consider the simplest possible spec you could give 100 programmers and receive no bugs in return.
There is only one or two https://pubs.opengroup.org/onlinepubs/9699919799/utilities/t... and maybe https://pubs.opengroup.org/onlinepubs/9699919799/utilities/f... .
Even "Hello, World!" is done wrong more often than not. An example: you should check for errors from `printf()`, as in [1].
[1]: https://stackoverflow.com/questions/12355758/proper-hello-wo...
EDIT: Yep, https://github.com/coreutils/coreutils/blob/master/src/true....
https://en.wikipedia.org/wiki/IEFBR14 was a one-byte program, but that had a bug, so it had to be doubled in size.
And yes, it still exists (https://www.ibm.com/docs/en/zos-basic-skills?topic=utilities...). I wouldn’t know how large it is nowadays.
Seriously, though, thank you for the link. That is good to know!
The core of the problem was noted already: Obviously most people can't read.
That's especially "funny" when thinking about all the fuss that is made about teaching children programming in school. They should start with teaching them reading.
I don't even mean this snarky. The state of affairs is actually depressing and I would welcome it very much if more people around would be able to read, understanding what's written. Would make a lot of things easier for everybody I guess.
This would likely require teaching students at least basic logic. This was entirely absent from my school experience.
It’s a hugely undertaught and undervalued skill, IMO. Before we start shoehorning CS into high school curriculums, we should consider laying these foundations first.
A program
* Not all programmers can understand all programs
* Most programs don't describe the problem exactly
* Almost no program describes the desired outcome exactly
(Also debatable, for example if correct operation of the program depends on some property of its environment that can't always be relied upon.)
Too many to rely upon this.
is not how I would convert an integer to string in objective-c!
I like these projects. Fun
https://news.ycombinator.com/invited
as reported by the unofficial