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

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)

Related

LabVIEW: How to share a .NET object created from LabVIEW

I have a class called Camera in the .NET library and once I instantiate the object I want to create a reference of it so that this instance can be used from other VIs. How do I make a reference or how do I make it global ?
Thanks,
There are a couple ways to approach your question.
Possible answer 1: You're looking to let multiple parallel subVIs use the object at the same time. The .NET wire is already a reference wire. Forking that wire does not copy the object. Just wire it into the other VIs, however many there are, and let them all use the reference.
Possible answer 2: You're trying to obtain the existing reference in another VI without passing the reference on a wire through a subVI conpane or Call By Reference node. In this case, you would pass the .NET object refnum the same way you would pass any other bit of data in LabVIEW when avoiding wires. In general, the rule is "avoid passing data outside of dataflow." Seriously... try to pass the refnum through a conpane... if this program is going to have any significant lifetime, you'll be happier when you can take that approach. BUT... when such outside-of-dataflow passing is necessary, there are many tools -- queues, notifiers, global VIs, data value references, functional globals. Which of those tools is the right one depends greatly on what you're actually trying to achieve. The simplest is to create a global VI, but that introduces a lot of polling checks as the second VI has to keep polling the global to see if the first VI has stored the value yet or not. A notifier refnum is probably the most flexible option that I can point you toward... create a named notifier of your .NET refnum type. Both first and second VI can obtain the notifier by name. The second VI then blocks on Wait For Notificiation waiting for the first VI to write the refnum into the notifier. See http://zone.ni.com/reference/en-XX/help/371361L-01/glang/create_notifier/ for more information on notifiers. Or Google the other terms that I listed if that seems insufficient for your needs.

Business logic in command design pattern

I use the command design pattern to deal with player actions.
For example, below is the command that handles a dice roll.
interface ICommand
{
public function execute(Game $game) : void;
}
class RollDiceCommand implements ICommand
{
private $player;
public function __construct(Player $player)
{
$this->player = $player;
}
public function execute(Game $game) : void
{
$dice = DiceFacade::roll(new NumberGenerator());
// Currently a business logic goes here
if ($dice->isDouble()) {
$player->incrementDoubleCount();
if ($player->getDoubleCount() === 3) {
$command = new GoToJailCommand();
$command->execute();
return;
}
} else {
// The next player turn
$game->nextPlayer();
}
$command = MoveForwardCommand($this->player);
$command->execute($dice->getValue());
// ...
}
}
Is it good idea to store an additional business logic in the command?
Should I call an another command directly from the roll command or I need to avoid it? The idea of throwing an event in the command seems better to me. What do you think about it?
Thank you!
The most used form of Command pattern in DDD (the one from CQRS) is not the same as the Go4 Command pattern. It is just a DTO with no execute() method.
In DDD the applicative logic is in the command handler/application service, not the command itself.
Note that a large part of the logic you currently have in execute() is domain logic and shouldn't even be in a command handler. Go to jail, Next player, Move forward - these look like domain rules that should be in the Domain layer.
Should I call an another command directly from the roll command or I
need to avoid it? The idea of throwing an event in the command seems
better to me. What do you think about it?
It depends if you consider the followup move to be part of the main action or an indirect consequence. Indirect commands are often executed as part of a separate transaction.
The Command pattern is useful when you want to encapsulate requests as an object. That allows you to pass parameters to them when they're instantiated, to group them together (executing them as a block), to log them, and even undo them.
I'm not seeing (yet) a reason you need this.
Is it good idea to store an additional business logic in the command?
One reason it's bad to store business logic (in the presentation layer) is that if you want to add another version of your application (say, a mobile version), you have to repeat the business logic code in the new application (in its presentation layer). Also, it's harder to maintain and test the business logic, because it's not really very well encapsulated (it's spread out).
Here, however, you've encapsulated some of it in a Command object, which may not be bad (depending on "where" you see this code). For the game of Monopoly, will you have multiple clients (different presentation layers?) or is this a pet project (one implementation)? If there are going to be different presentation layers, then it's best to keep the domain logic out of them. There's nothing in your sample code (but I'm not good with PHP) with Command that looks too tied to presentation, so it's probably OK.
Generally, if you're trying to encapsulate domain logic, the GoF Façade pattern is useful. You'd have a Façade class in the domain layer that handles the high-level operations (e.g., rollAndMove($dice)). It seems you already use a Façade for the dice roll. Player could alternatively be a class that plays the roll of the Façade, since the domain logic of taking a turn would be a reasonable responsibility for that class (IMO). Of course, if Player ends up with too many methods, it's perhaps better to use a separate class for the Façade.
The idea of throwing an event in the command seems better to me. What do you think about it?
I don't see a problem with combining both patterns, but perhaps you don't really need Command for what it's intended to be?
You're right that the execute() would be very short code (just call the Facade's method). However, using a Command object allows you to save the state of the game (e.g., GoF Memento pattern) if you wanted to undo the command later, or as stated above you could log the information in a standard way, etc. If you don't need those things, I would avoid using Command as it's adding complexity without the intent of the pattern.

Command pattern for restaurant use case

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. :))

Selecting the Correct View for an Object Type

I've had this problem many times before, and I've never had a solution I felt good about.
Let's say I have a Transaction base class and two derived classes AdjustmentTransaction and IssueTransaction.
I have a list of transactions in the UI, and each transaction is of the concrete type AdjustmentTransaction or IssueTransaction.
When I select a transaction, and click an "Edit" button, I need to decide whether to show an AdjustmentTransactionEditorForm or an IssueTransactionEditorForm.
The question is how do I go about doing this in an OO fashion without having to use a switch statement on the type of the selected transaction? The switch statement works but feels kludgy. I feel like I should be able to somehow exploit the parallel inheritance hierarchy between Transactions and TransactionEditors.
I could have an EditorForm property on my Transaction, but that is a horrible mixing of my UI peanut butter with my Model chocolate.
Thanks in advance.
You need to map your "EditorForm" to a transaction at some point. You have a couple options:
A switch statement...like you, I think this stinks, and scales poorly.
An abstract "EditorForm" property in base Transaction class, this scales better, but has poor seperation of concerns.
A Type -> Form mapper in your frontend. This scales fairly well, and keeps good seperation.
In C#, I'd implement a Type -> Form mapper like this:
Dictionary <Type,Type> typeMapper = new Dictionary<Type,Type>();
typeMapper.Add(typeof(AdjustTransaction), typeof(AdjustTransactionForm));
// etc, in this example, I'm populating it by hand,
// in real life, I'd use a key/value pair mapping config file,
// and populate it at runtime.
then, when edit is clicked:
Type formToGet;
if (typeMapper.TryGetValue(CurrentTransaction.GetType(), out formToGet))
{
Form newForm = (Form)Activator.CreateInstance(formToGet);
}
You probably don't want to tie it to the inheritance tree--that will bind you up pretty good later when you get a slight requirements change.
The relationship should be specified somewhere in an external file. Something that describes the relationship:
Editing AdujustmentTransaction = AdjustmentTransactionEditorForm
Editing IssueTransaction = IssueTransactionEditorForm
With a little bit of parsing and some better language than I've used here, this file could become very generalized and reusable--you could reuse forms for different objects if required, or change which form is used to edit an object without too much effort.
(You might want users named "Joe" to use "JoeIssueTransactionEditorForm" instead, this could pretty easily be worked into your "language")
This is essentially Dependency Injection--You can probably use Spring to solve the problem in more general terms.
Do I miss something in the question? I just ask because the obvious OO answer would be: Polymorph
Just execute Transaction.editWindow() (or however you want to call it), and
overwrite the method in AdjustmentTransaction and IssueTrasaction with the required functionality. The call to element.editWindow() then opens the right dialog for you.
An alternative to the Dictionary/Config File approach would be
1) to define a interface for each of the transaction editors.
2) In your EXE or UI assembly have each of the forms register itself with the assembly that creates the individual transaction.
3) The class controlling the registration should be a singleton so you don't have multiple form instances floating around.
3) When a individual transaction is created it pulls out the correct form variable from the registration object and assigns it do an internal variable.
4) When the Edit method is called it just uses the Show method of the internal method to start the chain of calls that will result in the display of that transacton editor.
This eliminates the need for config files and dictionaries. It continues to separate the UI from the object. Plus you don't need any switch statement
The downside is having to write the interface for each every form in addition to the form itself.
If you have a great deal of different types of editors (dozens) then in that case I recommend that you use the Command Pattern
You have a master command that contains the dictonary recommend by Jonathan. That commands in turns will use that dictornary to execute one of a number of other command that calls the correct form with the correct object. The forms continue to be separate from the object themselves. The forms reside in the Command assembly. In addition you don't have to update the EXE to add another editor only the Command assembly. Finally by putting things inside of Command you can implement Undo/Redo a lot easier. (Implement a Unexecute as well as a Execute)

What is Inversion of Control?

Inversion of Control (IoC) can be quite confusing when it is first encountered.
What is it?
Which problem does it solve?
When is it appropriate to use and when not?
The Inversion-of-Control (IoC) pattern, is about providing any kind of callback, which "implements" and/or controls reaction, instead of acting ourselves directly (in other words, inversion and/or redirecting control to the external handler/controller).
The Dependency-Injection (DI) pattern is a more specific version of IoC pattern, and is all about removing dependencies from your code.
Every DI implementation can be considered IoC, but one should not call it IoC, because implementing Dependency-Injection is harder than callback (Don't lower your product's worth by using the general term "IoC" instead).
For DI example, say your application has a text-editor component, and you want to provide spell checking. Your standard code would look something like this:
public class TextEditor {
private SpellChecker checker;
public TextEditor() {
this.checker = new SpellChecker();
}
}
What we've done here creates a dependency between the TextEditor and the SpellChecker.
In an IoC scenario we would instead do something like this:
public class TextEditor {
private IocSpellChecker checker;
public TextEditor(IocSpellChecker checker) {
this.checker = checker;
}
}
In the first code example we are instantiating SpellChecker (this.checker = new SpellChecker();), which means the TextEditor class directly depends on the SpellChecker class.
In the second code example we are creating an abstraction by having the SpellChecker dependency class in TextEditor's constructor signature (not initializing dependency in class). This allows us to call the dependency then pass it to the TextEditor class like so:
SpellChecker sc = new SpellChecker(); // dependency
TextEditor textEditor = new TextEditor(sc);
Now the client creating the TextEditor class has control over which SpellChecker implementation to use because we're injecting the dependency into the TextEditor signature.
Note that just like IoC being the base of many other patterns, above sample is only one of many Dependency-Injection kinds, for example:
Constructor Injection.
Where an instance of IocSpellChecker would be passed to constructor, either automatically or similar to above manually.
Setter Injection.
Where an instance of IocSpellChecker would be passed through setter-method or public property.
Service-lookup and/or Service-locator
Where TextEditor would ask a known provider for a globally-used-instance (service) of IocSpellChecker type (and that maybe without storing said instance, and instead, asking the provider again and again).
Inversion of Control is what you get when your program callbacks, e.g. like a gui program.
For example, in an old school menu, you might have:
print "enter your name"
read name
print "enter your address"
read address
etc...
store in database
thereby controlling the flow of user interaction.
In a GUI program or somesuch, instead we say:
when the user types in field a, store it in NAME
when the user types in field b, store it in ADDRESS
when the user clicks the save button, call StoreInDatabase
So now control is inverted... instead of the computer accepting user input in a fixed order, the user controls the order in which the data is entered, and when the data is saved in the database.
Basically, anything with an event loop, callbacks, or execute triggers falls into this category.
What is Inversion of Control?
If you follow these simple two steps, you have done inversion of control:
Separate what-to-do part from when-to-do part.
Ensure that when part knows as little as possible about what part; and vice versa.
There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.
--
The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word!
--
Examples
Event Handling. Event Handlers (what-to-do part) -- Raising Events (when-to-do part)
Dependency Injection. Code that constructs a dependency (what-to-do part) -- instantiating and injecting that dependency for the clients when needed, which is usually taken care of by the DI tools such as Dagger (when-to-do-part).
Interfaces. Component client (when-to-do part) -- Component Interface implementation (what-to-do part)
xUnit fixture. Setup and TearDown (what-to-do part) -- xUnit frameworks calls to Setup at the beginning and TearDown at the end (when-to-do part)
Template method design pattern. template method when-to-do part -- primitive subclass implementation what-to-do part
DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) -- COM/OS (when-to-do part)
Inversion of Controls is about separating concerns.
Without IoC: You have a laptop computer and you accidentally break the screen. And darn, you find the same model laptop screen is nowhere in the market. So you're stuck.
With IoC: You have a desktop computer and you accidentally break the screen. You find you can just grab almost any desktop monitor from the market, and it works well with your desktop.
Your desktop successfully implements IoC in this case. It accepts a variety type of monitors, while the laptop does not, it needs a specific screen to get fixed.
Inversion of Control, (or IoC), is about getting freedom (You get married, you lost freedom and you are being controlled. You divorced, you have just implemented Inversion of Control. That's what we called, "decoupled". Good computer system discourages some very close relationship.) more flexibility (The kitchen in your office only serves clean tap water, that is your only choice when you want to drink. Your boss implemented Inversion of Control by setting up a new coffee machine. Now you get the flexibility of choosing either tap water or coffee.) and less dependency (Your partner has a job, you don't have a job, you financially depend on your partner, so you are controlled. You find a job, you have implemented Inversion of Control. Good computer system encourages in-dependency.)
When you use a desktop computer, you have slaved (or say, controlled). You have to sit before a screen and look at it. Using the keyboard to type and using the mouse to navigate. And a badly written software can slave you even more. If you replace your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of your computer controlling it.
By implementing Inversion of Control, a software/object consumer gets more controls/options over the software/objects, instead of being controlled or having fewer options.
With the above ideas in mind. We still miss a key part of IoC. In the scenario of IoC, the software/object consumer is a sophisticated framework. That means the code you created is not called by yourself. Now let's explain why this way works better for a web application.
Suppose your code is a group of workers. They need to build a car. These workers need a place and tools (a software framework) to build the car. A traditional software framework will be like a garage with many tools. So the workers need to make a plan themselves and use the tools to build the car. Building a car is not an easy business, it will be really hard for the workers to plan and cooperate properly. A modern software framework will be like a modern car factory with all the facilities and managers in place. The workers do not have to make any plan, the managers (part of the framework, they are the smartest people and made the most sophisticated plan) will help coordinate so that the workers know when to do their job (framework calls your code). The workers just need to be flexible enough to use any tools the managers give to them (by using Dependency Injection).
Although the workers give the control of managing the project on the top level to the managers (the framework). But it is good to have some professionals help out. This is the concept of IoC truly come from.
Modern Web applications with an MVC architecture depends on the framework to do URL Routing and put Controllers in place for the framework to call.
Dependency Injection and Inversion of Control are related. Dependency Injection is at the micro level and Inversion of Control is at the macro level. You have to eat every bite (implement DI) in order to finish a meal (implement IoC).
Before using Inversion of Control you should be well aware of the fact that it has its pros and cons and you should know why you use it if you do so.
Pros:
Your code gets decoupled so you can easily exchange implementations of an interface with alternative implementations
It is a strong motivator for coding against interfaces instead of implementations
It's very easy to write unit tests for your code because it depends on nothing else than the objects it accepts in its constructor/setters and you can easily initialize them with the right objects in isolation.
Cons:
IoC not only inverts the control flow in your program, it also clouds it considerably. This means you can no longer just read your code and jump from one place to another because the connections that would normally be in your code are not in the code anymore. Instead it is in XML configuration files or annotations and in the code of your IoC container that interprets these metadata.
There arises a new class of bugs where you get your XML config or your annotations wrong and you can spend a lot of time finding out why your IoC container injects a null reference into one of your objects under certain conditions.
Personally I see the strong points of IoC and I really like them but I tend to avoid IoC whenever possible because it turns your software into a collection of classes that no longer constitute a "real" program but just something that needs to be put together by XML configuration or annotation metadata and would fall (and falls) apart without it.
Wikipedia Article. To me, inversion of control is turning your sequentially written code and turning it into an delegation structure. Instead of your program explicitly controlling everything, your program sets up a class or library with certain functions to be called when certain things happen.
It solves code duplication. For example, in the old days you would manually write your own event loop, polling the system libraries for new events. Nowadays, most modern APIs you simply tell the system libraries what events you're interested in, and it will let you know when they happen.
Inversion of control is a practical way to reduce code duplication, and if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control. Inversion of control is made easy in many languages through the concept of delegates, interfaces, or even raw function pointers.
It is not appropriate to use in all cases, because the flow of a program can be harder to follow when written this way. It's a useful way to design methods when writing a library that will be reused, but it should be used sparingly in the core of your own program unless it really solves a code duplication problem.
Suppose you are an object. And you go to a restaurant:
Without IoC: you ask for "apple", and you are always served apple when you ask more.
With IoC: You can ask for "fruit". You can get different fruits each time you get served. for example, apple, orange, or water melon.
So, obviously, IoC is preferred when you like the varieties.
Answering only the first part.
What is it?
Inversion of Control (IoC) means to create instances of dependencies first and latter instance of a class (optionally injecting them through constructor), instead of creating an instance of the class first and then the class instance creating instances of dependencies.
Thus, inversion of control inverts the flow of control of the program. Instead of the callee controlling the flow of control (while creating dependencies), the caller controls the flow of control of the program.
But I think you have to be very careful with it. If you will overuse this pattern, you will make very complicated design and even more complicated code.
Like in this example with TextEditor: if you have only one SpellChecker maybe it is not really necessary to use IoC ? Unless you need to write unit tests or something ...
Anyway: be reasonable. Design pattern are good practices but not Bible to be preached. Do not stick it everywhere.
IoC / DI to me is pushing out dependencies to the calling objects. Super simple.
The non-techy answer is being able to swap out an engine in a car right before you turn it on. If everything hooks up right (the interface), you are good.
Inversion of control is a pattern used for decoupling components and layers in the system. The pattern is implemented through injecting dependencies into a component when it is constructed. These dependences are usually provided as interfaces for further decoupling and to support testability. IoC / DI containers such as Castle Windsor, Unity are tools (libraries) which can be used for providing IoC. These tools provide extended features above and beyond simple dependency management, including lifetime, AOP / Interception, policy, etc.
a. Alleviates a component from being responsible for managing it's dependencies.
b. Provides the ability to swap dependency implementations in different environments.
c. Allows a component be tested through mocking of dependencies.
d. Provides a mechanism for sharing resources throughout an application.
a. Critical when doing test-driven development. Without IoC it can be difficult to test, because the components under test are highly coupled to the rest of the system.
b. Critical when developing modular systems. A modular system is a system whose components can be replaced without requiring recompilation.
c. Critical if there are many cross-cutting concerns which need to addressed, partilarly in an enterprise application.
Let's say that we have a meeting in a hotel.
We have invited many people, so we have left out many jugs of water and many plastic cups.
When somebody wants to drink, he/she fills a cup, drinks the water and throws the cup on the floor.
After an hour or so we have a floor covered with plastic cups and water.
Let's try that after inverting the control:
Imagine the same meeting in the same place, but instead of plastic cups we now have a waiter with just one glass cup (Singleton)
When somebody wants to drink, the waiter gets one for them. They drink it and return it to the waiter.
Leaving aside the question of the hygiene, the use of a waiter (process control) is much more effective and economic.
And this is exactly what Spring (another IoC container, for example: Guice) does. Instead of letting the application create what it needs using the new keyword (i.e. taking a plastic cup), Spring IoC offers the application the same cup/ instance (singleton) of the needed object (glass of water).
Think of yourself as an organizer of such a meeting:
Example:-
public class MeetingMember {
private GlassOfWater glassOfWater;
...
public void setGlassOfWater(GlassOfWater glassOfWater){
this.glassOfWater = glassOfWater;
}
//your glassOfWater object initialized and ready to use...
//spring IoC called setGlassOfWater method itself in order to
//offer to meetingMember glassOfWater instance
}
Useful links:-
http://adfjsf.blogspot.in/2008/05/inversion-of-control.html
http://martinfowler.com/articles/injection.html
http://www.shawn-barrett.com/blog/post/Tip-of-the-day-e28093-Inversion-Of-Control.aspx
I shall write down my simple understanding of this two terms:
For quick understanding just read examples*
Dependency Injection(DI):
Dependency injection generally means passing an object on which method depends, as a parameter to a method, rather than having the method create the dependent object. What it means in practice is that the method does not depends directly on a particular implementation; any implementation that meets the requirements can be passed as a parameter.
With this objects tell thier dependencies.
And spring makes it available. This leads to loosely coupled application development.
Quick Example:EMPLOYEE OBJECT WHEN CREATED,
IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT
(if address is defines as dependency by Employee object)
Inversion of Control(IoC) Container:
This is common characteristic of frameworks,
IOC manages java objects – from instantiation to destruction through its BeanFactory. -Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean's scope, lifecycle events, and any AOP features for which it has been configured and coded.
QUICK EXAMPLE:Inversion of Control is about getting freedom, more flexibility, and less dependency. When you are using a desktop computer, you are slaved (or say, controlled). You have to sit before a screen and look at it. Using keyboard to type and using mouse to navigate. And a bad written software can slave you even more. If you replaced your desktop with a laptop, then you somewhat inverted control. You can easily take it and move around. So now you can control where you are with your computer, instead of computer controlling it.
By implementing Inversion of Control, a software/object consumer get more controls/options over the software/objects, instead of being controlled or having less options.
Inversion of control as a design guideline serves the following purposes:
There is a decoupling of the execution of a certain task from implementation.
Every module can focus on what it is designed for.
Modules make no assumptions about what other systems do but rely on their contracts.
Replacing modules has no side effect on other modules I will keep things abstract here, You can visit following links for detail understanding of the topic.
A good read with example
Detailed explanation
I found a very clear example here which explains how the 'control is inverted'.
Classic code (without Dependency injection)
Here is how a code not using DI will roughly work:
Application needs Foo (e.g. a controller), so:
Application creates Foo
Application calls Foo
Foo needs Bar (e.g. a service), so:
Foo creates Bar
Foo calls Bar
Bar needs Bim (a service, a repository, …), so:
Bar creates Bim
Bar does something
Using dependency injection
Here is how a code using DI will roughly work:
Application needs Foo, which needs Bar, which needs Bim, so:
Application creates Bim
Application creates Bar and gives it Bim
Application creates Foo and gives it Bar
Application calls Foo
Foo calls Bar
Bar does something
The control of the dependencies is inverted from one being called to the one calling.
What problems does it solve?
Dependency injection makes it easy to swap with the different implementation of the injected classes. While unit testing you can inject a dummy implementation, which makes the testing a lot easier.
Ex: Suppose your application stores the user uploaded file in the Google Drive, with DI your controller code may look like this:
class SomeController
{
private $storage;
function __construct(StorageServiceInterface $storage)
{
$this->storage = $storage;
}
public function myFunction ()
{
return $this->storage->getFile($fileName);
}
}
class GoogleDriveService implements StorageServiceInterface
{
public function authenticate($user) {}
public function putFile($file) {}
public function getFile($file) {}
}
When your requirements change say, instead of GoogleDrive you are asked to use the Dropbox. You only need to write a dropbox implementation for the StorageServiceInterface. You don't have make any changes in the controller as long as Dropbox implementation adheres to the StorageServiceInterface.
While testing you can create the mock for the StorageServiceInterface with the dummy implementation where all the methods return null(or any predefined value as per your testing requirement).
Instead if you had the controller class to construct the storage object with the new keyword like this:
class SomeController
{
private $storage;
function __construct()
{
$this->storage = new GoogleDriveService();
}
public function myFunction ()
{
return $this->storage->getFile($fileName);
}
}
When you want to change with the Dropbox implementation you have to replace all the lines where new GoogleDriveService object is constructed and use the DropboxService. Besides when testing the SomeController class the constructor always expects the GoogleDriveService class and the actual methods of this class are triggered.
When is it appropriate and when not?
In my opinion you use DI when you think there are (or there can be) alternative implementations of a class.
I agree with NilObject, but I'd like to add to this:
if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control
If you find yourself copying and pasting code around, you're almost always doing something wrong. Codified as the design principle Once and Only Once.
For example, task#1 is to create object.
Without IOC concept, task#1 is supposed to be done by Programmer.But With IOC concept, task#1 would be done by container.
In short Control gets inverted from Programmer to container. So, it is called as inversion of control.
I found one good example here.
It seems that the most confusing thing about "IoC" the acronym and the name for which it stands is that it's too glamorous of a name - almost a noise name.
Do we really need a name by which to describe the difference between procedural and event driven programming? OK, if we need to, but do we need to pick a brand new "bigger than life" name that confuses more than it solves?
Inversion of control is when you go to the grocery store and your wife gives you the list of products to buy.
In programming terms, she passed a callback function getProductList() to the function you are executing - doShopping().
It allows user of the function to define some parts of it, making it more flexible.
I understand that the answer has already been given here. But I still think, some basics about the inversion of control have to be discussed here in length for future readers.
Inversion of Control (IoC) has been built on a very simple principle called Hollywood Principle. And it says that,
Don't call us, we'll call you
What it means is that don't go to the Hollywood to fulfill your dream rather if you are worthy then Hollywood will find you and make your dream comes true. Pretty much inverted, huh?
Now when we discuss about the principle of IoC, we use to forget about the Hollywood. For IoC, there has to be three element, a Hollywood, you and a task like to fulfill your dream.
In our programming world, Hollywood represent a generic framework (may be written by you or someone else), you represent the user code you wrote and the task represent the thing you want to accomplish with your code. Now you don't ever go to trigger your task by yourself, not in IoC! Rather you have designed everything in such that your framework will trigger your task for you. Thus you have built a reusable framework which can make someone a hero or another one a villain. But that framework is always in charge, it knows when to pick someone and that someone only knows what it wants to be.
A real life example would be given here. Suppose, you want to develop a web application. So, you create a framework which will handle all the common things a web application should handle like handling http request, creating application menu, serving pages, managing cookies, triggering events etc.
And then you leave some hooks in your framework where you can put further codes to generate custom menu, pages, cookies or logging some user events etc. On every browser request, your framework will run and executes your custom codes if hooked then serve it back to the browser.
So, the idea is pretty much simple. Rather than creating a user application which will control everything, first you create a reusable framework which will control everything then write your custom codes and hook it to the framework to execute those in time.
Laravel and EJB are examples of such a frameworks.
Reference:
https://martinfowler.com/bliki/InversionOfControl.html
https://en.wikipedia.org/wiki/Inversion_of_control
Inversion of Control is a generic principle, while Dependency Injection realises this principle as a design pattern for object graph construction (i.e. configuration controls how the objects are referencing each other, rather than the object itself controlling how to get the reference to another object).
Looking at Inversion of Control as a design pattern, we need to look at what we are inverting. Dependency Injection inverts control of constructing a graph of objects. If told in layman's term, inversion of control implies change in flow of control in the program. Eg. In traditional standalone app, we have main method, from where the control gets passed to other third party libraries(in case, we have used third party library's function), but through inversion of control control gets transferred from third party library code to our code, as we are taking the service of third party library. But there are other aspects that need to be inverted within a program - e.g. invocation of methods and threads to execute the code.
For those interested in more depth on Inversion of Control a paper has been published outlining a more complete picture of Inversion of Control as a design pattern (OfficeFloor: using office patterns to improve software design http://doi.acm.org/10.1145/2739011.2739013 with a free copy available to download from http://www.officefloor.net/about.html).
What is identified is the following relationship:
Inversion of Control (for methods) = Dependency (state) Injection + Continuation Injection + Thread Injection
Summary of above relationship for Inversion of Control available - http://dzone.com/articles/inversion-of-coupling-control
IoC is about inverting the relationship between your code and third-party code (library/framework):
In normal s/w development, you write the main() method and call "library" methods. You are in control :)
In IoC the "framework" controls main() and calls your methods. The Framework is in control :(
DI (Dependency Injection) is about how the control flows in the application. Traditional desktop application had control flow from your application(main() method) to other library method calls, but with DI control flow is inverted that's framework takes care of starting your app, initializing it and invoking your methods whenever required.
In the end you always win :)
I like this explanation: http://joelabrahamsson.com/inversion-of-control-an-introduction-with-examples-in-net/
It start simple and shows code examples as well.
The consumer, X, needs the consumed class, Y, to accomplish something. That’s all good and natural, but does X really need to know that it uses Y?
Isn’t it enough that X knows that it uses something that has the behavior, the methods, properties etc, of Y without knowing who actually implements the behavior?
By extracting an abstract definition of the behavior used by X in Y, illustrated as I below, and letting the consumer X use an instance of that instead of Y it can continue to do what it does without having to know the specifics about Y.
In the illustration above Y implements I and X uses an instance of I. While it’s quite possible that X still uses Y what’s interesting is that X doesn’t know that. It just knows that it uses something that implements I.
Read article for further info and description of benefits such as:
X is not dependent on Y anymore
More flexible, implementation can be decided in runtime
Isolation of code unit, easier testing
...
A very simple written explanation can be found here
http://binstock.blogspot.in/2008/01/excellent-explanation-of-dependency.html
It says -
"Any nontrivial application is made up of two or more classes that
collaborate with each other to perform some business logic.
Traditionally, each object is responsible for obtaining its own
references to the objects it collaborates with (its dependencies).
When applying DI, the objects are given their dependencies at creation
time by some external entity that coordinates each object in the
system. In other words, dependencies are injected into objects."
Programming speaking
IoC in easy terms: It's the use of Interface as a way of specific something (such a field or a parameter) as a wildcard that can be used by some classes. It allows the re-usability of the code.
For example, let's say that we have two classes : Dog and Cat. Both shares the same qualities/states: age, size, weight. So instead of creating a class of service called DogService and CatService, I can create a single one called AnimalService that allows to use Dog and Cat only if they use the interface IAnimal.
However, pragmatically speaking, it has some backwards.
a) Most of the developers don't know how to use it. For example, I can create a class called Customer and I can create automatically (using the tools of the IDE) an interface called ICustomer. So, it's not rare to find a folder filled with classes and interfaces, no matter if the interfaces will be reused or not. It's called BLOATED. Some people could argue that "may be in the future we could use it". :-|
b) It has some limitings. For example, let's talk about the case of Dog and Cat and I want to add a new service (functionality) only for dogs. Let's say that I want to calculate the number of days that I need to train a dog (trainDays()), for cat it's useless, cats can't be trained (I'm joking).
b.1) If I add trainDays() to the Service AnimalService then it also works with cats and it's not valid at all.
b.2) I can add a condition in trainDays() where it evaluates which class is used. But it will break completely the IoC.
b.3) I can create a new class of service called DogService just for the new functionality. But, it will increase the maintainability of the code because we will have two classes of service (with similar functionality) for Dog and it's bad.
Inversion of control is about transferring control from library to the client. It makes more sense when we talk about a client that injects (passes) a function value (lambda expression) into a higher order function (library function) that controls (changes) the behavior of the library function.
So, a simple implementation (with huge implications) of this pattern is a higher order library function (which accepts another function as an argument). The library function transfers control over its behavior by giving the client the ability to supply the "control" function as an argument.
For example, library functions like "map", "flatMap" are IoC implementations.
Of course, a limited IoC version is, for example, a boolean function parameter. A client may control the library function by switching the boolean argument.
A client or framework that injects library dependencies (which carry behavior) into libraries may also be considered IoC
I've read a lot of answers for this but if someone is still confused and needs a plus ultra "laymans term" to explain IoC here is my take:
Imagine a parent and child talking to each other.
Without IoC:
*Parent: You can only speak when I ask you questions and you can only act when I give you permission.
Parent: This means, you can't ask me if you can eat, play, go to the bathroom or even sleep if I don't ask you.
Parent: Do you want to eat?
Child: No.
Parent: Okay, I'll be back. Wait for me.
Child: (Wants to play but since there's no question from the parent, the child can't do anything).
After 1 hour...
Parent: I'm back. Do you want to play?
Child: Yes.
Parent: Permission granted.
Child: (finally is able to play).
This simple scenario explains the control is centered to the parent. The child's freedom is restricted and highly depends on the parent's question. The child can ONLY speak when asked to speak, and can ONLY act when granted permission.
With IoC:
The child has now the ability to ask questions and the parent can respond with answers and permissions. Simply means the control is inverted!
The child is now free to ask questions anytime and though there is still dependency with the parent regarding permissions, he is not dependent in the means of speaking/asking questions.
In a technological way of explaining, this is very similar to console/shell/cmd vs GUI interaction. (Which is answer of Mark Harrison above no.2 top answer).
In console, you are dependent on the what is being asked/displayed to you and you can't jump to other menus and features without answering it's question first; following a strict sequential flow. (programmatically this is like a method/function loop).
However with GUI, the menus and features are laid out and the user can select whatever it needs thus having more control and being less restricted. (programmatically, menus have callback when selected and an action takes place).
Since already there are many answers for the question but none of them shows the breakdown of Inversion Control term I see an opportunity to give a more concise and useful answer.
Inversion of Control is a pattern that implements the Dependency Inversion Principle (DIP). DIP states the following: 1. High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g. interfaces). 2. Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
There are three types of Inversion of Control:
Interface Inversion
Providers shouldn’t define an interface. Instead, the consumer should define the interface and providers must implement it. Interface Inversion allows eliminating the necessity to modify the consumer each time when a new provider added.
Flow Inversion
Changes control of the flow. For example, you have a console application where you asked to enter many parameters and after each entered parameter you are forced to press Enter. You can apply Flow Inversion here and implement a desktop application where the user can choose the sequence of parameters’ entering, the user can edit parameters, and at the final step, the user needs to press Enter only once.
Creation Inversion
It can be implemented by the following patterns: Factory Pattern, Service Locator, and Dependency Injection. Creation Inversion helps to eliminate dependencies between types moving the process of dependency objects creation outside of the type that uses these dependency objects. Why dependencies are bad? Here are a couple of examples: direct creation of a new object in your code makes testing harder; it is impossible to change references in assemblies without recompilation (OCP principle violation); you can’t easily replace a desktop-UI by a web-UI.
Creating an object within class is called tight coupling, Spring removes this dependency by following a design pattern(DI/IOC). In which object of class in passed in constructor rather than creating in class. More over we give super class reference variable in constructor to define more general structure.
Using IoC you are not new'ing up your objects. Your IoC container will do that and manage the lifetime of them.
It solves the problem of having to manually change every instantiation of one type of object to another.
It is appropriate when you have functionality that may change in the future or that may be different depending on the environment or configuration used in.