Lazy programmers do it inline

If there's one thing I've learned from writing a lot of jQuery, it's that you can write a whole lot of code without pressing the enter key. Between all the method chaining and inline functions, you can do quite a bit with a small amount of code.

One thing I never really bothered to realize before recently is that you can write inline functions anywhere you want in just about any programming language. In this example, I'll show you ActionScript 3. Remember, just because you can, doesn't mean you should: the point of a function is to be reusable. If you write a function inline, you can not use it in other places. The example I'm going to give is a good use of an inline function because the contents of the function are probably only used in this specific case.

Quick and Dirty Alert Confirmations

	Alert.show("Are you sure you want to do that?","Confirmation", Alert.YES|Alert.NO,this,
   (function(event:CloseEvent):void{
	if(event.detail == Alert.YES) dispatchEvent(new Event("SomeEvent"));
   }),null,Alert.NO);

A lot of times, we want to warn a user before they do something they will regret. This code, in the end, simply dispatches an event of type "SomeEvent" only if the user hit "yes". If they hit "no", nothing else will happen.

Another good example of this would be my aforementioned use of callLater. Anywhere a function is passed, you can do it inline. If you want to.

Alternative

	Alert.show("Are you sure you want to do that?","Confirmation", Alert.YES|Alert.NO,this,onConfirm,null,Alert.NO);

   private function onConfirm(event:CloseEvent):void{
	if(event.detail == Alert.YES) dispatchEvent(new Event("SomeEvent"));
   }

There's hardly any difference between the two except that the second one is reusable. Some developers cringe when they see stuff like this written inline and some think it is efficient. It's largely up to your style. If I've got more than a line or two of logic, I tend to write it out in its own function rather than inline.