views:

121

answers:

3

I'm quite new to this pattern...

+3  A: 

If you've got lambdas, you don't really need half of "design" "patterns" altogether.

Factory? That's just a function returning new objects. Visitor? Duh! Command? Anonymous function. Interpreter? Function which takes string or whatever. Strategy? It's a function!

That's just lambdas, functions and closures.

The problem is, about 1/3 to 1/2 of them were basically cover-ups for deficiencies in C++ that don't exist in other languages. Although I'm not a huge Perl fan anymore, I have to admit the Perl community caught on to this first (or at least funniest). They pointed out that many of these so-called patterns were actually an implementation of Functional Programming in C++.

So yes, you can use anonymous (or otherwise named) functions where you would use the Command pattern.

alamar
what's the difference between a lambda and an anonymous function?
Iain
They are synonyms, I guess.
alamar
Nope, there's slight differences - http://blogs.msdn.com/ericlippert/archive/2007/01/10/lambda-expressions-vs-anonymous-methods-part-one.aspx
Dan F
There isn't a difference between lambdas and anonymous functions.There's a difference "between lambdas and anonymous functions in C#".Yet nobody cares: in javascript, for example, there isn't.
alamar
yep, fair point, if I could edit the comment I would. Awesome yegge post btw!
Dan F
Usually, a lamda expression is an expression, while an anonymous function contains statements.
Niki
Usually where?In lisps, for example, lambda is lambda, no matter what's inside...
alamar
A: 

I would say no, on the basis that a function cannot really encapsulate the details of a command, and if it as anonymous how can both the caller and callee understand what it represents?

(If one wanted to be pedantic, the GoF description of the Copmmand pattern specifically describes the use of an object to do the encpsulation, preclusing a function based implenetation, though that would be nit-picking).

Visage
can you explain that in more detail? Which details can't be encapsulated?
Iain
+2  A: 

If your command supports only one operation, you can safely use an anonymous function.

However, it's not uncommon to have more than one operation for each command. E.g. DoCommand/UndoCommand for undo/redo-handling. Or CanExecuteCommand/ExecuteCommand to enabled/disable UI features for the command. Or something like GetLocalizedCommandName. I would use an interface in these cases (instead of e.g. a tuple of anonymous functions).

Niki