Command pattern for restaurant use case - oop

I just start to learn design patterns, one is the command pattern. After reading some materials and some documentations, such as
http://www.oodesign.com/command-pattern.html
https://www.tutorialspoint.com/design_pattern/command_pattern.htm
I got the idea of using command pattern for stock buying and selling. The client can first decide which stock he/she would like to sell or buy and then let the agent/broker to invoke the command's execute function. I think this makes sense.
While another 'classic' example is restaurant, which confuses me for quite a while. As a customer, how can a customer know which cook (receiver) will be able to cook the item (soup or grill in the example)? The cook shall be not decided by the customer I think. Can anyone point me out how I should approach this idea?
Thanks!

I believe you're not thinking about the restaurant example correctly. A customer doesn't give it's order directly to the cooks, a waitress takes the order to the kitchen and puts it in the queue where the cooks can take an order to make when they're available.
In code, this would look like a shared queue that the waitress adds to, and the cooks are in a continuous loop where they cook something then take the next order that they are able to cook. The command pattern in this example is simply the order that gets transferred from the customer to the kitchen.

Actually, your question is out of the scope of the problem what the command pattern actually tries to solve.
If you are familiar with Java, you can easy have an idea of Command Pattern from Java threads. Actually Thread.run() (not only run()) is command pattern in a nutshell.
The main idea is, if we have some group of objects (concrete Command objects which extends Command interface) which have an important functionality, implement that with a method which is not rigid with any method parameters or types. So that any invoker(CommandHandler) which wants to execute that functionality can actually execute that without knowing what the concrete class is. It can execute someCommandObject.execute();. Only requirement is to be an instance of Command interface.
In Java threads example, let's think about the JVM/Operating system. You know that any program goes to that level as a thread where the program in execution resides as that thread's process. So that thread executor can executes any threads process by anyThread.start(), anyThread.sleep() etc.
In the restaurant example the actual command objects are SoupOrder, GrillOrder etc. The CommandHandler is Waiter. Think about a situation where we introduce another command object called LunchOrder which is a child of Command class and implements void execute(){}. Now you don't have to make any change to the invoker (Waiter) since it still can call up lunchOrder.execute(). So the publishers(command objects) and client(invoker) implementation is decoupled. That's the beauty of Command pattern.
You may refer this also. :))

Related

LabVIEW: Programmatically setting FPGA I/O variables (templates?)

Question
Is there a way to programmatically set what FPGA variables I am reading from or writing to so that I can generalize my main simulation loop for every object that I want to run? The simulation loops for each object are identical except for which FPGA variables they read and write. Details follow.
Background
I have a code that uses LabVIEW OOP to define a bunch of things that I want to simulate. Each thing then has an update method that runs inside of a Timed Loop on an RT controller, takes a cluster of inputs, and returns a cluster of outputs. Some of these inputs come from an FPGA, and some of the outputs are passed back to the FPGA for some processing before being sent out to hardware.
My problem is that I have a separate simulation VI for every thing in my code, since different values are read from and returned to the FPGA for each thing. This is a pain for maintainability and seems to cry out for a better method. The problem is illustrated below. The important parts are the FPGA input and output nodes (change for every thing), and the input and output clusters for the update method (always the same).
Is there some way to define a generic main simulation VI and then programmatically (maybe with properties stored in my things) tell it which specific inputs and outputs to use from the FPGA?
If so then I think the obvious next step would be to make the main simulation loop a public method for my objects and just call that method for each object that I need to simulate.
Thanks!
The short answer is no. Unfortunately once you get down to the hardware level with LabVIEW FPGA things begin to get very static and rely on hard-coded IO access. This is typically handled exactly how you have presented your current approach. However, you may be able encapsulate the IO access with a bit of trickery here.
Consider this, define the IO nodes on your diagram as interfaces and abstract them away with a function (or VI or method, whichever term you prefer). You can implement this with either a dynamic VI call or an object oriented approach.
You know the data types defined by your interface are well known because you are pushing and pulling them from clusters that do not change.
By abstracting away the hardware IO with a method call you can then maintain a library of function calls that represent unique hardware access for every "thing" in your system. This will encapsulate changes to the hardware IO access within a piece of code dedicated to that job.
Using dynamic VI calls is ugly but you can use the properties of your "things" to dictate the path to the exact function you need to call for that thing's IO.
An object oriented approach might have you create a small class hierarchy with a root object that represents generic IO access (probably doing nothing) with children overriding a core method call for reading or writing. This call would take your FPGA reference in and spit out the variables every hardware call will return (or vice versa for a read). Under the hood it is taking care of deciding exactly which IO on the FPGA to access. Example below:
Keep in mind that this is nowhere near functional, I just wanted you to see what the diagram might look like. The approach will help you further generalize your main loop and allow you to embed it within a public call as you had suggested.
This looks like an [object mapping] problem which LabVIEW doesn't have great support for, but it can be done.
My code maps one cluster to another assuming the control types are the same using a 2 column array as a "lookup."

Test Driven Development in OOP, setting object state without using the public interface

Suppose I was writing a clone of the game 2048 (http://gabrielecirulli.github.io/2048/) and I want to write a test to verify that "the right thing" happens when the game is "won". Suppose that my game state is encapsulated in a class and that the state itself is private.
I suppose that I could write code to play the game, evaluate through the public interface when I'm about to win and then make the winning move; however, this seems like overkill. I would instead like to set a game state, make the winning move and verify that the object behaves as expected.
What is the recommended way of designing such a test? My current thought is that the test should either be a public member function of the class or that the test infrastructure should be friended by the class. Both of these seem distasteful.
Edit: In response to the first question: I'm assuming in this example that I don't have a method to set the game state and that there's no reason to write one; therefore it would be adding additional functionality just to write a test... ...one that then requires another member function to test, a get game state function. So then I'm writing at least two more public methods and test just to write this one test. Worse, these are methods that essentially break encapsulation such that if the internal details change I have to change these two methods and their tests for no other reason than to have a test. This seems more distasteful than friending a test function.
First, remember that Test-Driven Development is a design-oriented methodology. The primary goal of the tests is to influence the design of the SUT and its collaborators; everything else is just along for the ride.
Second, TDD emphasizes small steps. In his book, Test-Driven Development: By Example, Kent Beck says:
If you have to spend a hundred lines creating the objects for one single assertion, then something is wrong. Your objects are too big and need to be split. (p. 194)
This means you should listen to your intuition about writing the code necessary to win the game being overkill.
You also said:
I would instead like to set a game state, make the winning move and verify that the object behaves as expected.
Which is exactly what you should do.
Why? Because you're testing end-game scenarios. Most/all of the details that led to the end-game are irrelevant - you just want to make sure the program does "the right thing... when the game is won." As such, these are the only details that are relevant to your tests.
So what are these details that are relevant to your tests? To figure them out, it helps to discuss things with a colleague.
Q: How does the test configure the system to indicate the game has been won - without actually playing the game?
A: Tell something that the game has been won.
Q: What object would the test tell that the game has been won?
A: I don't know. But to keep things simple, let's say it's some object serving the role of "Referee".
By asking these questions, we've teased out some details of the design. Specifically, we've identified a role which can be represented in OOP by an interface.
What might this "Referee" role look like? Perhaps:
(pseudocode)
begin interface Referee
method GameHasBeenWon returns boolean
end interface
The presence of an interface establishes a seam in the design, which allows tests to use test-doubles in place of production objects. Not only that, it allows the implementation of this functionality to change (e.g., a rule change affecting how a game is determined to be "won") without having to modify any of the surrounding code.
This ties in directly with something else you mentioned:
I'm assuming in this example that I don't have a method to set the game state and that there's no reason to write one; therefore it would be adding additional functionality just to write a test...
A test is a consumer of your code. If it is difficult for a test to interact with your code, then it will be even more difficult for production code (having many more constraints) to interact with it. This is what is meant by "Listening to your tests".
Note that there are a lot of possible designs that can fall out of TDD. Every developer is going to have their own preferences which will influence the look and feel of the architecture. The main takeaway is that TDD helps break your program up into many small pieces, which is one of the core tenets of object oriented design.

Why is the Command Pattern convenient in Object-Oriented Design?

I don't understand why a Command pattern is convenient in object-oriented design.
Instead of using, e.g. the Command Switch which has a reference to the Lamp class, can't I just create a Switchable abstract class and invoke its methods?
In this way I'm decoupling the invoker and receiver anyway, and I don't have to create a Command object for each receiver class.
Your Switchable creates an abstraction between invoker and receiver but they are still coupled (invoker has needs a reference to the receiver). The Command pattern lets you create that decoupling. The invoker says to some intermediate component "Hey I've got this command I'd like to be executed" and then the intermediate thing can dynamically pass that request on to the receiver.
ps... I'm guessing you pulled the Switch example from wikipedia. That's a pretty bad example of why this pattern is useful. Take a look at a better examples.
Suppose you want to make a list like this:
Turn on lamp
Set A/C temperature
Play "Moon River"
The actions and receivers are all different, so you need an abstraction that is decoupled from all of them. The Command pattern also comes in handy when you want to support undo/redo or similar things.
Lets look at it like: When client wants the receiver to execute some task, then client has two options,
Call Receiver and tell him to execute the task.
Call some third party who knows receiver, and third party will pass the message to receiver.
First option looks better, as think of scenario, when there is no waiter to take order in restaurant and you have to go to chef to tell him what you want.
OR suppose you lost your remote and you have to go to TV and manually switch the button.
It provides flexibility so that command can be executed not only in synchronous mode, but also in Asynchronous mode.
You -> Switch -> Light
Here the switch decouples you and the light. So it makes it easier to turn on/off lights using switch. this is use (convenience) in using command pattern.
You - Command Invoker
Switch - Command Manager
Command - Turn On/Off
Light - Actual implementer
If command pattern is not there you have to manually put the light in holder when needed and remove it when not needed.
No. You can not do the same as a command do with the abstraction. In fact every time you can do the work of a pattern and anything else with another way you can do. But when you change the Switcher from concrete to abstract that you must do this for a right design regardless of command pattern, you are only decoupling the client of switcher form its implementation and not decoupling the switcher(i.e Invoker) from Lamp(i.e. Receiver) because at last you must have a reference to Lamp in the concretes of Switcher that is equals to have it in Switcher. Note is here that the Lamp is a concrete and you can not change it to abstract. So when you have a concrete and you are working with it many time and many other attribute, you must use Command Pattern to decouple the Switcher form Lamp by move dependency of Switcher to Lamp inside Command class and depend Switcher to an intermediate class i.e. Command. In addition I think the sample in Wikipedia is very useful.
The command pattern offers a structured way of associating user actions with system commands.
By implementing the Command pattern, you can have a structured technique of storing the user's command and thus allow actions such as undo/redo.
For instance, implementing the Command pattern for a simple text editor (GOF - Chapter 2) would look like this:
By storing a undoRedoPointer, we can achieve the undo/redo operation by increasing/decreasing the counter each time a command is executed without violating the object's encapsulation. This is a result of combining the command and the memento design pattern.
Think of each 'command' object as a live object or task that knows how to perform something by its own. Your invoker is just a queue or list that can
1) hold all these command objects and
2) execute them in order/fashion that you liked to.
This model is so flexible in terms of a handler, isn't it? The invoker can buffer, prioritize or follow any algorithm when performing the tasks.
I believe through Command Pattern multiple invokers can use the same command. For e.g., In case of editor, copy functionality (or algo) is required to be invoked from command (ctrl+c) or from menu.
So if you wouldn't have implemented command pattern, copy algo would have been tightly coupled with ctrl+c command, and would have been difficult for you to reuse to be invoked from editor menu.
So it looks like this ...
Ctrl+C action --> CopyCommand --> Copy algo
Menu copy command --> CopyCOmmand --> Copy algo
As you can see from above, the source of command is changing, but destination is same (copy algo)

Object Oriented Design problem

If I`m programming a game in which there is a worker that cuts wood (from trees), where would I put the "cutWood" method, in the worker class, or the tree class?
EDIT:
The first example I read on OOD was about a circle (a class called circle) which has in it a method called "calculate area".
Now, sure enough a circle doesn't calculate its own area.
The only way to think of it is that calculating area is an operation that is relevant to the circle (an operation done on the circle)
So, cutWood method is relevant to both, the worker, and the tree.
I don't see any cohesion to have a wood cutting method in the worker. The cutting is done on the tree, and should therefore be part of the tree class. Presumably, cutting the wood will also involve changing some internal state of the wood class too.
A worker should call the cut method on whatever tree he wants, rather than the tree telling the worker that he should cut it. If you want to abstract this like Hans has hinted at, you could make an ICuttable interface for the Cut method, and have your tree implement it.
Consider something you're familiar with, a String. When you want to cut a string (split), you don't define a splitString method in every object which is going to do this. Whatever object decides to split the string, the same thing takes place - and will usually need to know the internals of the target object (the string) in order to do it. Many other objects simply call the split method of the string. The string object has high cohesion - because it's methods contribute to a common task - manipulating strings.
I don't see how cutting wood contributes much to the worker object itself.
Ask yourself: Do workers cut wood, or do trees cut wood?
You basically answered it in your question: "a worker that cuts wood". You should put it to the worker class.
Create a
cut(Material m)
method for the worker for extra object-orientedness.
do you have to modify the tree as it is being cut?
do you have to modify the worker as it cuts a tree?
i would imagine you'd end up with a WoodCutting service which handles the event possibly modifications to both, or in turn calling worker.cutWood() AND tree.woodCut()
ahah what a question ;)
Sounds like a candidate for the Strategy pattern to me. You may need a WorkerAction abstract class with a performAction method. Then subclasses of the WorkerAction class will implement the details such as cutting a tree, digging for gold and other worker actions. So the sub class knows about the details of the tree and can call the necessary methods on the tree to affect the tree as it is being cut.
The worker class then only need a reference to an instance of a concrete WorkerAction on which it calls performAction(). The worker does not know the details of the Tree or the Gold etc. This way the worker can perform the action but you are not limiting the worker to only one action. In fact you no longer need to modify the worker class if you want your worker to do more actions in the future.
You could have a cutWood method in the worker class, and a cutted method in the tree class. Obviously, worker.cutWood calls tree.cutted, which might return the amount of wood harvested.
tree.cutted would do all the stuff that is necessary to let the tree die.
If you consider method calls as "messages sent from one object to another", it makes a lot more sense to say "the player sends a 'cut wood' message to the worker who in turn sends a 'cut' message to the tree".
Object design is all about assigning responsibilities to your classes. That means there really is no good answer to this question. As it all depends how you model the responsibilities in your design. (see: Larman)
Thus you need to decide what object/class is responsible for what. This will lead you to correct answers on question about were to place what kind of methods.
Thus ask you’re selves questions like: does the worker decide on his own to cut wood? If he does, he probably does not need to be ordered so, thus he will not have a need for a method cut(tree). But if the user can order him to do that, he will need a cut(tree) method. An other example: does the tree have to know he is cut? Well, if a cut tree just leads to his removal from the forrest, he might not have a need for such a tree.cut() method. But if you assign to the tree the responsibility to (re)draw himself during cutting, you might have a need for a tree.cut() method. The tree could even be modeled as having a width and that he can calculate how many cuts are needed before he collapses.
Since a single worker might cut more than one tree, it sounds more likely that you'd want to put cutWood() in the worker class.
Doesn't the cut() method go on the Saw object?
More seriously, I think of the target of the method call as the "subject", the method itself as a "verb", and its parameters (if the verb is transitive) as "direct objects." So, in this example, it would be worker.cut(tree).
This question can only really be answered if you explain what cutWood does.
If cutWood only affects the state of a Tree then it belongs in Tree e.g.,
public void cutWood() {
this.height = 0;
}
In the case of calculateArea you only need the radius of a circle (assume pi is constant) to do this calculation - nothing else. That's why it belongs in Circle.
Stop trying to model the real world too closely and look at what your method actually needs to do.
This is an intresting topic. I thought about a likewise scenario myself sometimes. I think a good way to go, is to put the method into the class with the highest cohesion. Therefore the Tree class would be the first choice. On the otherhand if you try to match a real world model i would say the Worker class has to be able to perform some kind of actions which includes cutting a Tree. I often find myself in these kind of situations and wonder where is the right place to put this method. Another approach would be a class which knows about worker and tree's, and therefore handles the cutting tree meachnism. This way both classes (tree,worker) would not know anything about it.

Singleton pattern - doubt in Head First Design Patterns book

On page 175, there is an example of Chocolate Boiler class. Something like this:
public class ChocolateBoiler {
private boolean empty;
private boolean boiled;
public ChocolateBoiler {
empty = true;
boiled = false;
}
// and then three methods to fill, drain and boil which changes the
// status of these two flag depending of situation
}
In section "brain power" they ask a question "How might things go wrong if more than one instance of ChocolateBoiler is created in an application?"
I'm not sure what's the problem with this class. Why do we introduce a singleton pattern here? These two flags are not static and so one per instance. So how creating more than one instance can mess things up?
The question isn't about making an instance of an object.
It's about the confusion caused by having two instances of the object, both of which purport to have the status of the ChocolateBoiler.
If some Object (for example, Cooker) thinks it has the status of the ChocolateBoiler, and some other Object (for example, Recipe) things it has the status of the ChocolateBoiler, what happens now?
Since the variables are instance variables, the ChocolateBoiler objects won't agree on the status of the ChocolateBoiler. Now what happens?
It's only a problem if there only can be one ChocolateBoiler, and if there only can be one, it should be a singleton.
I believe in that example you only had only ONE Chocolate boiler. And so you should only be able to create one instance of the object representing it. If you were allowed to create multiple instances, you would then perhaps issue the command if (boiler.hotEnough()) boiler.stop() somewhere in you system and would be surprised that although the boiler is already way too hot, it's not stopping because you are talking to some 'dead' instance of a Boiler, which returns hotEnough() : false.
Using the singleton pattern you are making sure that no matter where in your code you say Boiler.getInstance() you will get the one and only boiler object there is, and that when you then talk to it, it will do as you would expect.
The entire example of the chocolateboiler in a singleton bothered me a lot while I was reading it.
On a really fundamental level, I don't see why its necessary when you only have one physical thing, to enforce that fact in software. What happens if you get another one? what are you going to do, add the second to the same singleton? make 2 different singletons? a simple global variable would do the job.
IMO, its not the boiler itself that you can only have one thing of , its access to that particular boiler's controls. You can't allow a second person to start making a new batch of chocolate while its already in that process for someone else, or even allow the same person to make a second batch before the first is finished. From that point of view, a simple queueing or batch processing system would do the job. Using another pattern from the book, the command pattern would be a much better way of handling it , as there's only one waitress , and all new orders get queued up until the cook's done with the current food order. (er, if you haven't seen the book, what I just said might not make much sense, sorry)
Maybe I'm just not getting the point. I haven't done much OOP or anything with design patterns before, and I'm losing job opportunities because of it, so I'm reading up on it.