1

If I want a function to do something different the first time it's run, I could check each time it's run to determine whether it's the first time, or I could change the function; something like this:

foo=function(a,b){
    ...do something1...
    foo=_foo;
}
_foo=function(a,b){
    ...do something2...
}

Is this bad; if so, why? Is there a better way to do this? I'm specifically looking to implement this in javascript, though other language points will be considered.

user1277170
  • 3,127
  • 3
  • 19
  • 19
  • 1
    It really depends on how you want to modify the function. Often, this is used for caching, so it's just an performance-enhancement that the user of the function shouldn't notice. If that's the case, then it's fine. If not, you might need to elaborate on your specific case. – kba Jan 06 '14 at 19:47
  • I usually use a static variable (property) as a flag to handle "first time run" scenarios – CrayonViolent Jan 06 '14 at 19:47
  • 1
    Almost always bad. Back in the day we'd write self-modifying code for resource-constrained systems, of which your browser is not one. Even memoizing isn't really a great excuse, IMO, but that's not a technical debate. – Dave Newton Jan 06 '14 at 19:48
  • 3
    functions are objects. you'd be better off having one function, with a simple `if (!foo.hasrun) { foo.hasrun = true; first time code; } else { next run code }` type thing going. – Marc B Jan 06 '14 at 19:48

1 Answers1

1

This isn't a "self-modifying" function in the strict sense - you don't modify any code on the fly (and that would be bad), just assign another value to a function name. This is fine in most cases and makes polymorphic code quite simple and elegant. To make the intent cleaner, you can factor out the "first time" code into a separate function:

function firstTimeFoo() {
    .....
    foo = normalFoo
}

function normalFoo() {
    ...
}

foo = firstTimeFoo
georg
  • 211,518
  • 52
  • 313
  • 390