JadenSimon / proposal-defer

MIT License
2 stars 0 forks source link

Would `finally` be better? #2

Open JadenSimon opened 2 weeks ago

JadenSimon commented 2 weeks ago

We don't have to use word defer if it isn't the best fit. Many of the user discussions regarding using seem to mention finally a lot. I've even caught myself using finally to explain defer. So maybe for JS developers, finally makes the most sense.

finally await file.close()
finally {
  ...
}

I'm liking this idea more and more. We're just taking the existing finally syntax and "freeing" it from the try statement. As well as allowing it to exist without a block.

Possible problems

The finally statement must not diverge from what users expect from the finally block of a try statement. Even nuanced behavior could significantly diminish usability. The difference in code flow when mixed with try/finally seems potentially problematic:

finally 4;
finally 3;

try {
} finally {
  1;
}

finally 2;

The order of execution for finally statements does seem to contradict the finally block's sequential behavior. Feels like a show stopper to me.

Another problem: finally after a close curly brace } can be easily confused as being apart of a try statement. There doesn't seem to be a good solution for this. Enforcing that a finally statement cannot immediately follow a block could work. This would require users to prepend a semicolon:

function foo() {
// code here
}
;finally {}

Of course, this isn't the common case.

martinheidegger commented 2 weeks ago

I have wondered about this as well, but I was too worried for it to be causing confusion with try/finally and thought that defer would be better as it is a concept in other languages.