8 ms·
*in Javascript. In most other languages where unwanted extra arguments raise an error instead of being silently ignored, this mostly isn't a problem
by craigds 6y ago
*in Javascript.
In most other languages where unwanted extra arguments raise an error instead of being silently ignored, this mostly isn't a problem
- choeger 6y agoIn a language that actually tries to help you creating error-free code, a type check would prevent this. This is really just a wonderful example how javascript is a mental burden to the programmers instead of a useful tool.
- dsego 6y agoHow would a type check prevent this?
- choeger 6y agoA type check would give map a type, say [a] -> (int -> a -> b) -> [b]. If you try to apply it to any function that does not have the type (int -> a -> b), the check would fail.
- username90 6y agoSo basically any language that does any form of type checking at all.
- MaxBarraclough 6y agoNot including TypeScript.
- xsmasher 6y agoJust to clarify, if you update toReadableNumber to take a second parameter and that parameter is not a number, typescript will complain.* TypeScript won't catch the original landmine because it ignores the extra parameters; maybe some linter would? Is there a rule that enforces "functions used by map must spell out all the parameters?" * Example of typescript giving an error on toReadableNumber_v2: https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBAQwE5IQTzgXjgbQIwA0ATAQMwC6A3MDQGYCuEIMAlpHDGAEoCmCAJggBGAGx4A5egFshPJAAoI0gFxKZcgJQBvYHD1wkPGPSQQ4agHScAYiwAePfvKIbqAXxrAGTVu068BYTFJdSQAfQA3IkUVNVkkAjgAB0Nae2VYJBYIAHNtXX1DY1Nk1Ps4AGpzaSswWwcnF3cacGgwMQsRMBz5RBR0CykEJN7-PkFRCWl4uA1Z6hbIKHaeTu7e5FQ0QeHR7nGgqdDIoln5miA https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBAQwE5...
- wruza 6y agoSee also magicalhippo’s comment on overloading. We could introduce real types instead of primitives, so that ‘number_formatting_base_t’ would conflict with ‘array_index_t’, but nobody in the world bothers beyond bare ‘int’.
- kuschku 6y agoActually, that's what I use inline types in kotlin for. So username, password are distinct from string and objectid might be backed by an int, but is distinct from int. Obviously, once compiled, there's no overhead, it's a zero cost abstraction. But an incredibly useful one.
- username90 6y agoYeah, I see the point, in for example C# if you have overloaded methods it tries it best to map it to the accepted type. However you'd have to work really hard to invent a case where a library updates a signature to accept another type, and then you in your code have 2 overloads of a method that you pass and it now choses the wrong version, all while the library change doesn't break any other code. Scenario: Library changes signature so you always pass functions with more parameters. Result: This will break almost every codebase, they probably wouldn't do this in a minor patch. Scenario: Library adds a new signature where you can pass functions with more parameters and keep them overloaded between each other. Result: Compiler can't identify which of the two signatures to pass your overloaded function and throws a compilation error.
- Akronymus 6y agoOn my personal projects with F#, never got a chance to use it professionally, I actually use them. Makes modeling the data much easier.
- btinker 6y agoIt would check the arguments and return type of the function. Map takes a function with three arguments, toReadableNumber only takes one, therefore the functions are of a different type. So someNumbers.map(toReadableNumber) would be an error and not execute at all, instead of being a "bad practice" / potential mistake.
- dsego 6y agoWhat if toReadable also takes 3 args of the same type but different meaning?
- flohofwoe 6y agoYou can create custom types to communicate semantics to the type checker. Whether that's always a good idea is arguable though, but the tools are there (e.g. there's a wide field between weak and strong typing, and an overly strong type checker can be quite a hassle to work with while an overly weak type checker isn't much better than duck typing).
- magicalhippo 6y agoWell the issue mentioned is that map calls the callback function with up to three arguments[1]. A type check could prevent this because it would require map to take a reference to a function with three parameters, or the compiler would complain inside the map implementation. Similarly, passing it a function with only one parameter would be a type violation and the compiler would complain. Now in a language with type checking, you could still potentially run afoul. Say the map function was overloaded with one variant for one-parameter callbacks, one variant for two-parameter callbacks etc. Then the compiler might figure out it could use the second overload if the "toReadableNumber" function got changed to take the extra "base" parameter. So again you end up with the numbers getting converted with a variable base. Though, IMHO, having such an overloaded map function is inviting trouble and is a very poor design. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- mr_toad 6y ago> or the compiler Functions can be assigned at runtime. It would have to be a runtime error.
- dirkt 6y agoA proper typesystem for functional types will check at compile-time that in all places where you would assign such a function, the function will always have the right type. So it's NOT a runtime error, it's a compile-time error, even though you can assign different functions at runtime.
- mr_toad 6y agoYou can assign a reference to a function and pass that to a function that expects a callback, and then change that assignment based on incoming data. And if that’s not enough you can create and modify functions at runtime. And you’d have to content with JavaScript’s spread syntax and rest parameters. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- schwartzworld 6y agoIf your code has tests, an API change like the one described in the article would get caught immediately. And it only works because `Array.prototype.map` callback has one required arguments and two optional ones. What language with optional function arguments protects you from this sort of behavior? Do people in that language not test this sort of behavior? Or at least run through the app? More than that, the whole hurrdurr-javascript-bad thing is so tired. Lots of work is being done in JavaScript. Sure, it has its quirks, but those quirks come with expressiveness. You can use functional or imperative style, throw lambdas around, and it runs on pretty much all the phones and computers in the world.
- sfvisser 6y ago> What language with optional function arguments protects you from this sort of behavior? Languages with a sane type system. TypeScript has no issues catching such mistakes. Writing tests to catch simple type errors is such an incredible waste of time.
- tom_mellior 6y agoThe article has a whole section called "TypeScript doesn't solve this", with examples and stuff. Is it mistaken?
- sfvisser 6y agoPartially. TypeScript doesn't complain when you pass in a function that ignores some of its arguments. Which is totally fine and safe. If you upgrade your function from no second argument to a numeric second argument TypeScript will not complain and your program might break. It will not crash, because it still perfectly type-safe, but it might not behave like you want to. So in that sense the article has a point. However, this is just one instance of a larger issue with changing the behavior of a function, while keeping the types compatible. - Using a function as a callback to .map() with two numeric arguments and then swapping the arguments. - Returning a tuple of two of the same type and swapping the order. - Returning a string in a new encoding. - ... Basic rule: if it's a type error and the program might crash, TypeScript will complain. If the types are fine and only the behavior changes, TypeScript will (obviously) not complain. Callback functions and optional arguments are not special in this regard.
- lliamander 6y agoI'm not terribly impressed with claims that some programming language will hinder a programmer's development of their skills, but a language that teaches its users to reflexively avoid passing functions as arguments in this way is definitely concerning.
- foldr 6y agoYou mean to avoid passing named functions? The suggested alternative still passes a function. Although unnecessarily wrapping a named function in a lambda is bad code style (in most languages), it doesn’t seem that disastrous of a habit to get into.
- Geminidog 6y agoYou should be impressed by it. The true nature of type checking is basically a method of hindering you. The set of all correct programs is much smaller then the set of all programs that exist so anything that hinders a programmer from operating in the bigger parent set outside the set of correct programs is a good and impressive thing. What’s going on here is a type checking issue. JavaScript and typescript is a little too loose. The map method takes a function of <Arity 3, 2, or 1> So if a library changes a function from <arity 1> to <arity 2 or 1> you should get a type error, but the type checker is too loose. It’s subtle. Basically a type of <arity 3, 2, or 1> should only type check with <arity 3> or <arity 2> or <arity 1> it should not allow <arity 2 or 1>. You see what’s going on here? Subtle. This is indeed as much of a type checker problem as it is defining what type correctness is. The definition above is simply a way of defining type correctness that fits with our intuition of what is correct for this given situation, so take what I wrote with a grain of salt. There could be situations where the current definition of type correctness in typescript is more correct then the definition I provided. Our intuition is complex and if you think long and hard enough you may be able to come up with a formal definition of type correctness that perfectly fits our intuition and therefore elegantly unionized typescripts looser definition of correctness and my own stricter definition. Beware though, often human intuition can be contradictory. This means that a formalization of our intuitive notions of type correctness will also be contradictory and therefore unusable. In other words there may not be a way to type check for this issue while maintaining the convenience of the status quo. Intuitively I think it’s possible, you just need special syntax to tell the type checker whether to use my stricter definition or the original looser definition that’s in use now. Also I’m not sure if there’s any type checker in existence that handles that case (don’t know). So I believe this is more than just a JavaScript issue.
- Chris_Newton 6y agoIt also provides a useful example of the limitations of TypeScript’s type checking. TS is an improvement on JS in this area, but sometimes people overestimate the safety guarantees it offers and forget that its type system is still unsound.
- keyle 6y agoExactly, Typescript still remains a, transpiler.
- fulafel 6y agoI don't think we can excuse it by citing the nature of source-to-source compilers. Other languages like Haxe, Elm, ReasonML, ClojureScript etc that target JS don't suffer from this.
- searchableguy 6y agoUnsound type system was a sacrifice made for easy migration from javascript.
- MaxBarraclough 6y agoDoes Dart handle it better?
- sfvisser 6y agoTypeScript trivially catches the mistake: const func = (i: number, x: boolean) => i * 2 const nope = [1, 2, 3].map(func) // type error!
- Blikkentrekker 6y agoThis would have been one of the things one would expect to be fixed in strict mode.
- z3t4 6y agoYou should check the parameters. For example: function toReadableNumber(num, base, trap) { if(base == undefined) base = 10; if(typeof base != "number") throw new Error("Second argument should be the base! base=" + base + " (" + (typeof base) + ")"); if(trap != undefined) throw new Error("Did not expect a third argument. Are you using this with map? Then use an intermediate function.");
- kayodelycaon 6y agoThis won't help in most cases, because you're not going to be able to get the people writing libraries to add guards to every single function they make. This is a problem that should be handled at the language level, not by adding multiple lines of potentially incorrect code for every dozen lines of regular code.
- z3t4 6y agoYou do not have to add "guards" to every function, just the functions publicly available via API. And you only need to add them when making (breaking) changes, like adding more parameters, but most of the time you can figure out what the caller wants to do and keep your code backwards compatible. Also you should wait until your API is somewhat stable before adding the guards. So for most code, you do not need guards. But if your code is used by many, that defensive coding/guards, taking only a few minutes to add, will save countless man-hours that would otherwise be spent debugging. As a general rule I like errors to throw early. So when I found a bug, (I first write a test to automatically reproduce the bug, then) I backtrack and add guards to each step (with helpful debug/data in the error message), so that the bug would be caught at the surface, rather then causing weird issues several layers down. And guards are much easier to write then complicated type definitions. And the errors will be more informative, helpful and human friendly then errors from a type-checker. Defensive coding is mostly useful in long living apps that have a lot of state, and which is constantly developed (new features added, breaking changes, etc). You would not need defensive code in programs that are executed once and then thrown away.
- franciscop 6y agoI personally prefer extra arguments to just be ignored (and allow to use a default like `function fn(a, b='x') {`). I also believe in most other _dynamic_ languages this is allowed, so it's just about what kind of language it is, not just JS vs the rest.
- masklinn 6y ago> I also believe in most other _dynamic_ languages this is allowed Most definitely not. It's not allowed in Python, it's not allowed in Ruby, it's not allowed in any Lisp I know of[0], … it is allowed in PHP, which is about what I'd expect from that[1]. In most dynamic languages the arity is not a suggestion[2]. Which is exactly the issue at hand: `Array#map` was (stupidly) defined as calling its callback with 3 parameters. The last 2 are useless 99.99% of the time (and in better language you'd compose them in if and only if you needed them), as a result it's almost universal that you'd pass single-parameter callbacks which works… until it doesn't because the callback now takes 2+ parameters and starts taking in account the previously ignored garbage `Array#map` feeds it. The average JS developer likely doesn't even know Array#map callbacks receive 3 parameters, and usually aren't going to think about it: in 99% of cases it's has no relevance whatsoever. [0] but most lisps make significant uses of variable-arity functions, which is a very different and much more formal proposition [1] PHP's one saving grace being that HoFs have historically not been much of a thing, though I have not tracked how it's used these days [2] as long as it's present at all AFAIK in Perl functions don't have formal parameters lists
- franciscop 6y agoThis seems to work on Python: def hello(a, b = 'world'): print(a, b) hello('hello') hello('hello', 'world') But these don't, so fair point: hello('hello', 'world', 'there) # nor def hello(a): ... hello('hello', 'world')
- username90 6y agoYeah, problem with JavaScript function signatures is that every function argument is optional, including all the arguments you didn't write. In python those functions would look like: def F(a = None, b = None, *args): ... And you can't write any other kind of function in javascript. I don't really like that aspect of javascript, it creates so many hard to debug situations.
- deleted 6y ago[deleted]
- lloeki 6y agoIn Ruby there’s a similar situation. While blocks, procs, and lambdas all have arity metadata, only lambdas check for the argument count when called. The other two drop excess arguments and fill missing arguments with nil.
- Toutouxc 6y agoI think this problem is almost nonexistent in Ruby. If you're inlining your block as a literal do-end block on the call site, it's just a matter of knowing what kind of data you're calling the block-taking method on. So blocks are kinda different. If you're designing a more intricate piece of code to be used repeatedly by a 'map' or 'reduce' (like in the example), nothing is preventing you from defining a lambda instead of proc. And nothing is preventing you from designing your library so that it exposes only arity-checking lambdas to the outside. But it's also quite usual to define callbacks as plain old methods (e.g. Rails before and after actions). Methods can be easily used as a block by getting the actual Method object first with the 'method' method, then using the & syntax to automatically convert them to a proc (e.g. map(&method(:foobar)) which again, converts them to arity-checking lambdas.
- lloeki 6y agoYep the problem is very much reduced but it still exists: an API/DSL provider that hinges on blocks can change the args under your feet and it would only blow up when the argument values start to receive unexpected methods, instead of at the interface. As you mentioned, lambdas and methods check for that, but it’s sad to have to give up the syntactic and lexical niceties of blocks.
- chadlavi 6y agoI was about to say, just use typescript and it'll throw you an error that the function expected one argument but received three.