3 ms·
> Pyhon's design sin is that it fails to distinguish the binding of a variable from assignment. The programmer cannot locally (i.e. just in that statement alone
by adrianmsmith 3y ago
> Pyhon's design sin is that it fails to distinguish the binding of a variable from assignment. The programmer cannot locally (i.e. just in that statement alone) express "I expect this statement to be freshly creating a variable, introducing it into the scope, with value 42" and "I expect to be assigning value 42 to a variable which already exists in the scope (or else this should be diagnosed)".
I'm not entirely sure this is a bad thing? I'm learning Go right now, and I'm encountering plenty of code like:
err := DoFoo()
if err != nil ....
err = DoBar()
if err != nil ....
The problem with that is that if you remove the DoFoo line you have to change the DoBar line, even though nothing's really changed there. An (albeit small) waste of time, an extra thing to think about which has nothing to do with the problem you're solving, more lines to review in the PR, and more chance of merge conflicts later.
- hamdouni 3y agoYou can avoid this by using : if err := DoFoo(); err != nil { ... The 'err' variable will be local to the 'if' so you can write also : if err := DoBar(); err != nil { ... It is also nice to write it in one line :-)
- vips7L 3y agoYou've just hit Go's design flaw: error handling.
- kazinator 3y agoYou could bind the variable each time, if that is allowed: err := DoFoo(); if err != nil ... err := DoBar() if err != nil ... DoFoo and DoBar are different functions; their error return might not even be the same type. If mixed declarations and statements are not supported: { err := DoFoo(); if err != nil ... } { err := DoBar() if err != nil ... } this is what I do in C to reduce the scope of variables, and it has the benefit over the former example in that we delimit where the scope begins and ends. We know that after the closing brace, nothing can be referencing that err variable. (I'm not a fan of mixed decls and statements). Modern languages should support binding a variable in if: if (err := DoFoo()) { // err scoped here } My first example would be "bad" according to David Betz because it perpetrates shadowing.