javascript-decorators icon indicating copy to clipboard operation
javascript-decorators copied to clipboard

Allow decorators for functions as well

Open svieira opened this issue 9 years ago • 69 comments

Decorators for classes, methods, and object properties are a really nice extension to the language. The only extra one I would like to see is the ability to add decorators to function declarations:

@RunOnce
function expensiveOperation() {
    return 1 + 1;
}

de-sugars to:

var expensiveOperation = RunOnce(function expensiveOperation() {
  return 1 + 1;
});

This suggests allowing decorators for any assignment, but I think that might be a bit much so I'm leaving it out of this PR:

// For the curious, that would allow constructs like this
@RunOnce
let expensiveOp = () => 1 + 1

// De-sugars to

let expensiveOp = RunOnce(() => 1 + 1);

svieira avatar Mar 18 '15 21:03 svieira

The issue with adding decorators to function declarations is that they're hoisted which means hoisting the decorators too which changes the position in which they're evaluated.

sebmck avatar Mar 19 '15 09:03 sebmck

True, and that is a potential foot-gun, but I cannot think of any cases where source position is likely to be needed at run-time (I can see using decorators as targets for compile-time transformations using sweet-js, but in those cases the function hoisting behavior does not apply.) As I understand it, hoisting is likely to (though not specified to) happen in order, so even if you had a stateful decorator that added each decorated function to a queue, the functions would still run in order.

Am I just being dense and missing an obvious use case where source position could make or break functionality?

svieira avatar Mar 19 '15 12:03 svieira

Some examples:

var counter = 0;

var add = function () {
  // this function isn't even accessible if the decorator evaluation is hoisted
  // ie. done before `var counter = 0;`
  counter++;
};

@add
function foo() {

}

// what is the value of `counter`?
// if it's hoisted then it would be 2 when logically it should be 1

@add
function foo() {

}
var readOnly = require("some-decorator");

// is the evaluation hoisted?
// if so `readOnly` wont be defined if not then any reference to `foo` before the
// decorator will get the bare function
@readOnly
function foo() {

}

The behaviour is non-obvious and it's impossible to sprinkle to get obvious behaviour. It's similar to class declarations not being hoisted because their extends clause can be an arbitrary expression.

sebmck avatar Mar 19 '15 12:03 sebmck

Chuckles Fair enough - thanks for taking the time to point out the issues!

svieira avatar Mar 19 '15 12:03 svieira

The noted problems here suggest to me that decorators are possibly going to have very much the same problem as operator overloading is supposed to have.

The major concern I have with decorators is people writing too many decorators with not very good names. Or even for things that are pretty complicated. The concern I have is that decorators are only syntactic sugar to make code more declarative. But I hope they won't end up creating code that is often misleading and full of surprises.

I personally don't think any feature's merits should be judged by considering the worse use-cases. But I think it's still interesting to think about them to remove as many footguns as possible.


Relevant Point: Perhaps, functions decorators SHOULD work for functions. But since hoisting is the problem, Hoisting could be disabled for any function that is decorated. Since Function assignments work the same way, I don't think its too confusing.

nmn avatar Apr 09 '15 22:04 nmn

@nmn

But since hoisting is the problem, Hoisting could be disabled for any function that is decorated. Since Function assignments work the same way, I don't think its too confusing.

It is confusing. Function declarations that are hoisted sometimes isn't going to cut it.

sebmck avatar Apr 09 '15 22:04 sebmck

@sebmck Fair point.

Thinking about it more, perhaps they are no so important for functions.

Functions that take take and return functions are pretty easy to write. They are more useful in classes as the syntax keeps things from getting hairy.

Thanks.

nmn avatar Apr 09 '15 22:04 nmn

Why are they not important for functions? Memoize is just as needed in functions as well as in classes. Also for currying, who doesn't curry their functions ;)

If problem is you can accidentally use class decorators in functions, maybe another syntax:

@@memoize
function something() {
}

double at, or something.

Edit: Is hoisting really a problem? Being used Python a lot which implements function decorator, I don't think the order of decoration is used to anything except in bad code, which is really hard to safeguard anyway.

Ciantic avatar Apr 17 '15 08:04 Ciantic

@spleen387 Hoisting is still a problem.

sebmck avatar Apr 17 '15 16:04 sebmck

first a question: do generator functions get hoisted? If not isn't that confusing as well.

If yes, there is already a proposal for making custom wrappers around generators, like async functions.

async function x(){}
// becomes
function x(){
  return async(function*(){
    ...
  })()
}

How does this proposal deal with hoisting?

nmn avatar Apr 17 '15 23:04 nmn

Another approach, let the function get hoisted. But the decorator should be applied where it is defined.

So this:

var readOnly = require("some-decorator");

@readOnly
function foo() {

}

will desugar (and hoist) to:

function foo() {
}
var readOnly = require("some-decorator");

foo = readOnly(foo)

nmn avatar Apr 17 '15 23:04 nmn

Generator function declarations are definently hoisted. Hoisting the function declaration and not the decorator is unintuitive and confusing. You can just wrap the function in a method call and it expresses the exact same thing without the confusing semantics.

On Friday, 17 April 2015, Naman Goel [email protected] wrote:

Another approach, let the function get hoisted. But the decorator should be applied where it is defined.

So this:

var readOnly = require("some-decorator");

@readOnly function foo() {

}

will desugar (and hoist) to:

function foo() { } var readOnly = require("some-decorator");

foo = readOnly(foo)

Reply to this email directly or view it on GitHub https://github.com/wycats/javascript-decorators/issues/4#issuecomment-94097610 .

Sebastian McKenzie

sebmck avatar Apr 17 '15 23:04 sebmck

@sebmck I just updated my first comment. How does compositional functions deal with hoisting?

You can just wrap the function in a method call and it expresses the exact same thing without the confusing semantics. I get that, but the same could be said about classes as well.

I don't like the idea of decorators for only classes, and I'm just trying to find a solution to the hoisting problem. I feel like having decorators for only classes makes the language more disjointed and inconsistent than it already is.

nmn avatar Apr 17 '15 23:04 nmn

I get that, but the same could be said about classes as well.

Classes don't hoist so they don't suffer from the same problem that disallow function declaration decorators.

I don't like the idea of decorators for only classes, and I'm just trying to find a solution to the hoisting problem.

This isn't an intuitive solution to the hoisting problem and whatever solution is going to be an extreme hack.

sebmck avatar Apr 18 '15 00:04 sebmck

This isn't an intuitive solution to the hoisting problem and whatever solution is going to be an extreme hack.

In that case, perhaps decorators aren't a great idea after all? Wouldn't having decorators for class methods but not normal functions be equally confusing, hacky and inconsistent?

nmn avatar Apr 18 '15 14:04 nmn

In that case, perhaps decorators aren't a great idea after all?

How are you getting that decorators aren’t a good idea just because you can’t put them on function declarations because of hoisting? An entire feature shouldn’t be nerfed because of one nefarious case.

Wouldn't having decorators for class methods but not normal functions be equally confusing, hacky and inconsistent?

No, because class methods aren’t function declarations.

On Sat, Apr 18, 2015 at 7:51 AM, Naman Goel [email protected] wrote:

This isn't an intuitive solution to the hoisting problem and whatever solution is going to be an extreme hack.

In that case, perhaps decorators aren't a great idea after all? Wouldn't having decorators for class methods but not normal functions be equally confusing, hacky and inconsistent?

Reply to this email directly or view it on GitHub: https://github.com/wycats/javascript-decorators/issues/4#issuecomment-94170865

sebmck avatar Apr 18 '15 16:04 sebmck

No, because class methods aren’t function declarations.

Fair enough. I still have my reservations, but my intent was only to have a discussion about this.

nmn avatar Apr 19 '15 22:04 nmn

How are you getting that decorators aren’t a good idea just because you can’t put them on function declarations because of hoisting? An entire feature shouldn’t be nerfed because of one nefarious case.

I imagine how people begin to write single method classes only to get decoration feature enabled where basic function could satisfy... While decorator functions can be applied without decorator syntax that's noisy and inconsistent.

@sebmck you're the best of us aware of ES(any). Any change to kill this hoisting behavior ever? That is hoisting that allows to use undefined vars hiding syntax errors until runtime. Right? Probably the worst JS language aspect :imp:

ivan-kleshnin avatar Apr 22 '15 06:04 ivan-kleshnin

Any change to kill this hoisting behavior ever? That is hoisting that allows to use undefined vars hiding syntax errors until runtime. Right? Probably the worst JS language aspect

There's zero chance of function hoisting ever going away.

I imagine how people begin to write single method classes only to get decoration feature enabled where basic function could satisfy...

Let's explore what a function decorator would be (ignoring hoisting)

function memoize() {
  // do something...
}

@memoize
function myFunc() {
  // do something else...
}

Ignoring the aspect of hoisting, this would be equivalent to:

function memoize() {
  // do something...
}

var myFunc = memoize(function() {
  // do something else...
});

There's no way someone would rather do this:

function memoize(desc) {
  // do something...
  desc.value = value;
  return desc;
}

class MyFuncClass {
  @memoize
  myFunc() {
    // do something else...
  }
}

let myFuncInstance = new MyFuncClass();
myFuncInstance.myFunc();

So yeah we're left with sticking with this:

var myFunc = memoize(function() {
  // do something else...
});

or adding function decorators:

@memoize
function myFunc() {
  // do something else...
}

and because of hoisting function decorators become impossible.

So what's the point of this?

jamiebuilds avatar Apr 22 '15 08:04 jamiebuilds

@thejameskyle I want to believe something like SaneScript deprecation machinery at compiler level could handle such cases.

ivan-kleshnin avatar Apr 22 '15 08:04 ivan-kleshnin

@ivan-kleshnin Do you mean behind a directive?

sebmck avatar Apr 22 '15 08:04 sebmck

@sebmck, yes. I just want to express my opinion that language without at least tiny amount of deprecation process or at least "workaround modes" can't exist forever. Not breaking the web motto sounds good, but complexity grows and grows and we still lack a lot of things... I'm seriously considering to just drop everything and move to ClojureScript or other language which can evolve because it's not bound by backward compatibility craziness. Babel is truly awesome but a lot of things can't be fixed at the transpiler level without serious deviations from ES specs. JS still sucks at enterprise scale. I understand why people continue to use Ruby and other languages on backend.

ivan-kleshnin avatar Apr 22 '15 10:04 ivan-kleshnin

To solve this a lot of companies enforced the use of function expressions over function declaration. In fact once you change a function declaration to an expression you get different semantics.

To give this use case more power ES6 now asks the function expression to be named after the variable name.

Also, for succinctness you can go full-arrows here:

const myFunc = memoize(( ) => {
  //
});

yuchi avatar Apr 22 '15 12:04 yuchi

It's been a very useful discussion.

  1. I agree with @sebmck that the feature should not be nuked for one feature. Honestly it is simpler to wrap functions in functions that classes right now, so decorators are more useful for classes anyway.
  2. However, this discussion is becoming a discussion about succinctness. I think the point of decorators is to make things look more declarative. I would like to argue that passing classes through functions is relatively short to write as well.
  3. I was interested in this: https://github.com/jhusain/compositional-functions Generator functions are also hoisted, and it works by making a function that returns a function. So it applies the transformation at call time. I realize that it may not be the best idea for normal functions.

nmn avatar Apr 22 '15 22:04 nmn

Compositional functions are different as the grammar only allows ImportedBinding:

CompositionFunctionDeclaration : ImportedBinding [no LineTerminator here] function BindingIdentifier ( FormalParameters ) { FunctionBody } This means that you can only do import foo from “foo”; foo function bar() {}.

Imports are also hoisted so they’ll be bound before the function declarations are.

On Wed, Apr 22, 2015 at 11:11 PM, Naman Goel [email protected] wrote:

It's been a very useful discussion.

  1. I agree with @sebmck that the feature should not be nuked for one feature. Honestly it is simpler to wrap functions in functions that classes right now, so decorators are more useful for classes anyway.
  2. However, this discussion is becoming a discussion about succinctness. I think the point of decorators is to make things look more declarative. I would like to argue that passing classes through functions is relatively short to write as well.
  3. At this point, I really want to discuss this: https://github.com/jhusain/compositional-functions

Generator functions are also hoisted. So how does it work?

Reply to this email directly or view it on GitHub: https://github.com/wycats/javascript-decorators/issues/4#issuecomment-95353509

sebmck avatar Apr 22 '15 23:04 sebmck

The recent Angular weekly meeting notes suggests this is up for discussion again. Is it?

hannahhoward avatar Jun 04 '15 06:06 hannahhoward

From what I call tell in #7, it seems like syntax/grammar(?) is still in flux... However, based on babel's current behavior, it kinda sucks that the following works for class declarations and not functions:

import bar from './bar'

// Works
@bar
export class Foo {}

// Doesn't work
@bar
export function foo () {}

Why not allow functions to be decorated by other hoisted values? (i.e. other functions and imports)

cesarandreu avatar Jul 27 '15 14:07 cesarandreu

I'm curious why this issue would have been closed. If one agrees that there is a strong case for decorators, certainly it should apply in equal measure to functions. The current spec is designed to provide decorators for functions, but then says you can have them only if they're members of some class or object.

I'm wondering if there's a bit of anti-function sentiment at work here--something like, "real men use objects and classes and member functions, not wimpy plain old functions", or "in real frameworks like Exxxx everything is an object and since all I really want is syntactic sugar for writing computed properties why do I need decorators on anything other than literal object methods?".

AFAICT the only issue here is hoisting. But to jump from that to saying we can't decorate functions at all seems to be throwing out the baby with the bathwater. If we can't figure out how to have a single, coherent decoration mechanism, we should throw in the towel. The hoisting issue seems to be a red herring to me. For instance, the following code has well-understood, if counter-intuitive behavior:

function foo() {
    console.log(x);    // undefined
    var x = 99;
    console.log(x);    // 1
}

No one would claim that this is obvious, but that's the way the language works. By the same token, one could handle the function/hoisting/decorator case as follows:

function bazify(fn) { fn.baz = 99; return fn; }

function foo() {
    console.log(bar.baz);  // undefined

    @bazify
    function bar() { }

    console.log(bar.baz);    // 99
}

This is no more or less confusing or anti-intuitive than existing behavior from hoisting vars. The effect would be exactly the same as the desugared version below:

function foo() {
  console.log(bar.baz);  // undefined

  function bar() { }
  bar = bazify(bar);

  console.log(bar.baz);    // 99
}

To put it another way, for consistency with current hoisting behavior the decorator would not be hoisted. The decorator would have similar behavior to the initial value in a var statement.

Oops, just noticed this is precisely what @nmn proposed, which seems eminently reasonable.

rtm avatar Aug 02 '15 15:08 rtm

Just in case this helps somebody - I've gathered a couple of workarounds for decorating functions in a composable way into one article here: https://rreverser.com/ecmascript-decorators-and-functions/

Let me know if I missed something.

RReverser avatar Aug 08 '15 02:08 RReverser

The decorator would have similar behavior to the initial value in a var statement.

ES6 is adding let and const because they weren't happy with var's semantics. Those variables act differently if referred to before defined:

function foo() {
    console.log(x);    // throws an exception
    let x = 99;
    console.log(x);
}

Making functions be hoistable but decorators are only applied on the line they're used is like making a function half hoistable in a worst of both worlds way. If you consider decorators that critically change the behavior of a function like a RunOnce decorator, then splitting up the definition of the function from the application of the decorator in a way (accidentally) visible to other code can surely only lead to confusion. Applying a decorator like that should be done in a way such that the undecorated function isn't ever visible to any other code but the decorator itself.

Macil avatar Aug 25 '15 23:08 Macil