On Tuesday 05 November 2002 12:37 pm, Henri Yandell wrote:
> I would think of a Closure as:
>
>
> closure foo = { int i=0; i++ }
>
int i = 0;
closure foo = {i++};
return foo;
//elsewhere
evaluate foo;
Of course, that's some other language. In java, anonymous inner classes
approximate closures:
final IntHolder h = new IntHolder();
h.i = 0;
return new Command() {
public void execute() {h.i++;}
};
//elsewhere
c.execute();
> or some such. So you're right in that closure is not the right name.
>
> But Command is also not the right name. The Command pattern implies Undo
> and Argument and Results and not just:
>
Command often has a subtype, Undoable, Nnot all commands are undoable.
FileSave is a good example. You generally can't back out of that.
CommitTransaction is another. Undoable adds unexecute(), which backs out what
execute() does. Undo and redo is just walking up and down the command list.
It does require that ALL the state be present in the Command for execution and
unexection.
> public void do(Object).
>
Traditionally, execute() doesn't take any arguments. They're supplied when the
command object is created. It's a fairly old Smalltalk idiom. c.v. Design
Patterns.
>
> Any other words?
>
I'm looking at what's in Collections now. It's neither a Closure or a Command.
It's an UnaryOperation, or LambdaExpession. An unnamed function is applied to
all elements in a collection.
> Hen
>
The real thing is that Command doesn't imply a closure. Here's a dummied up
version of both
---- TestClosure.java ----
public class TestClosure {
public static void main(String[] args) {
IntHolder h = new IntHolder();
Command c = getCommand(h);
c.execute();
c.execute();
IntHolder h2 = new IntHolder();
Command c2 = getCommand(h2);
c2.execute();
c2.execute();
c.execute();
Command c3 = new IncIntCommand(h2);
c3.execute();
c3.execute();
c2.execute();
}
static Command getCommand(IntHolder h) {
final IntHolder i = h;
i.i = 7;
Command c = new Command() {
public void execute() {
i.i++;
System.out.println(i.i);
}
};
return c;
}
}
interface Command {
public void execute();
}
class IntHolder {
public int i = 0;
}
class IncIntCommand implements Command {
public IntHolder h;
public IncIntCommand(IntHolder h) {
this.h = h;
}
public void execute() {
h.i++;
System.out.println(h.i);
}
}
---- end ----
IncIntCommand is not a closure by any means. But it is a Command. Not much of
one, to be sure. But it's functionally the same as the closure version.
The reason for closures is that it keeps you from littering the landscape with
single use classes. In real life, the body of the closure might access many
stack variables, and it's easier to keep extending as you add more local
state.
--
To unsubscribe, e-mail: <mailto:commons-dev-unsubscribe@;jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@;jakarta.apache.org>