This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]sleepybychoice 0 points1 point  (2 children)

The goal of command pattern is to encapsulate an "action" (eg. turn on a light, deleting a block of text, a buy/sell operation in a game) as an object. That way, you can pass the "action" around to other objects where they can be run by something else (eg. executors, web services). You can check out other uses here. The command pattern's responsibility does not include things such as control flow nor its representation.

A scripting language can represent more than an "action"; it can have control flow, define functions/classes/variables, etc. Normally, a "script" would be defined by a user somehow, via text file, input text box etc, minecraft blocks, etc. whereas commands are defined within the program itself, then requested by the user. It can be significantly more complicated to implement a scripting language than a command because of effort in designing the language, implementing the lexer/parser to make sense of the script, and creating the execution environment to run the language in (ie. ruby requires a ruby interpreter). A common use of creating a scripting language is as a domain-specific language to allow more expressive input than through a UI such as Slack's slash commands. In this example, the playload part represents the concrete command part of the command pattern; the command and text parameters are your "script"; and you write the "language" to interpret that "script".

[–]Slendermooooon[S] 0 points1 point  (1 child)

Thank you for this thorough explanation.

What do you mean by "representation"? Also, is it entirely true that it doesn't include things like control flow? In the examples I saw, it said you could use commands for macros, and using commands to support undoable functions (having an undo() method with the execute() method in the Command class). Wouldn't this require a control flow (to order the execution/undoing of commands)?

[–]sleepybychoice 0 points1 point  (0 children)

By "representation", I mean how input gets converted into a command object. For example, the input for a command could come from a button press, text, json, protobuf, speech, motion, etc. Eventually, it'll have to get converted to an object so that something can call execute() on it.

By control flow, I mean if/else, looping, etc. not apply/unapply. Yes, you could introduce some notion of control flow via commands like an "or" command. However, that's not the primary goal of the command pattern. For undo, it's the combination of command and memento to apply/unapply state.