Is dependecy injection specific to obejct-oriented pattern? - angularjs

I come from server side language background (Symfony2). What I know is that dependency injection and service-oriented architectures are specific to object oriented programming. From their documentation:
Structuring your application around a set of independent service
classes is a well-known and trusted object-oriented best-practice.
These skills are key to being a good developer in almost any language.
I am reading now a client-side framework documentation (AngularJS), precisely the dependency injection chapter. Is angularJs written with OOP? Someone please to help me understand.
Thanks for your usual help.

The concept of dependency injection is based on the following ideas:
An entity (object, module, etc.) should not programmatically create the entities it depends upon.
Those dependencies should instead be passed as parameters (injected) instead.
This reduces unwanted coupling and allows other implementations to be substituted more easily (e.g., alternative data sources, stubs or mocks for testing)
As Doug Luce states in his answer, this concept can apply in other programming paradigms as well. The term is most common in object oriented circles because:
The origin of (programming) design patterns was object oriented programming.
Dependency Injection can alleviate the tendency of large object oriented programs to become too tightly coupled, difficult to test and brittle to change.
In some situations, such as pure functional programming, there is less need for something like dependency injection (it tends to happen naturally).
In structural languages without object oriented features, the concept is still very useful (perhaps even more so). Obvious and easily used mechanisms for dependency injection are not agreed upon in (non object oriented) structural languages.
Since JavaScript has both object oriented and functional features, I would expect AngularJS programmers to make full use of these features and use dependency injection when appropriate.

When the concept is called "dependency injection," it's almost always couched in the verbiage of object-oriented patterns. But the idea of passing in a wad of executable code that the function can use only depends on the language system having a way to do that: function types, closures, monads, promises, or whatever might do the trick.

Related

What is the advantage of using AngularJS dependency Injection? [duplicate]

I have been working with Angular for some time now, and I fail to see how it is an improvement from my previous way of coding.
First, I can't see what's wrong with having a central object to hold your project. After all, the injector is a singleton that looks up your dependencies into a central place, so Angular does have a central object, it's just hidden. Namespacing doesn't necessarily mean coupling, if it's done properly. And even when it's done, you don't need every single object of your code to be loosely coupled with the others. Besides, anytime you create a standalone JS script, you have to wrap it into Angular to make them play nice together.
Second, it's very verbose to declare all your dependencies everytime (especially with minification), so there is no gain from the readability point of view compared to proper namespacing.
Third, the performance gain is minimal. It forces me to use singletons everywhere, but I can do that on my own if I need to, and most of the time, I don't (network and DOM manipulations are my bottleneck, not JS objects).
In the end, I like the "enhanced" HTML and the automatic two-way bindings, but I can't see how the injection makes it any better than the way other frameworks deal with dependencies, given that it doesn't even provide dynamic loading like require.js. I haven't see any use case where I say to myself "oh, this is where it's so much better than before, I see" while coding.
Could you explain to me what benefits this technical choice brings to a project?
I can see only one for now: convention and best practice enforcement. It's a big one to create a lib ecosystem, but for now I don't see the fruit of it in the Angular community.
For me there are few aspects of how Angular's dependency injection is improving my projects, which I will list here. I hope that this will show you how OTHERS can benefit from it, but if you are well organised and experienced JS developer, then perhaps it might not be the same case for you. I think at some point this is just the matter of developing your own tools and coding guide.
Unified, declarative dependency resolving
JS is dynamic language (that's new, huh?) which gives a lot of power and even more responsibility to the programmer. Components can interact with each other on various ways by passing around all sorts of objects: regular objects, singletons, functions, etc. They can even make use of blocks of code which were not even mentioned to be used by other components.
JS has never had (and most likely never will) a unified way of declaring public, private or package (module) scopes like other languages have (Java, C, C#). Of course there are ways of encapsulating logic, but ask any newcomer to the language and he will simply don't know how to use it.
What I like about DI (not only in Angular, but in general) is the fact that you can list dependencies to your component, and you are not troubled how this dependency got constructed. This is very important for me, especially that DI in Angular allows you to resolve both kinds of components: these from the framework itself (like $http), or custom ones (like my favorite eventBus which I'm using to wrap $on event handlers).
Very often I look at the declaration of a service and I know what it does and how it does it just by looking at dependencies!
If I was to construct and/or make use of all those objects deep in the component itself, then I would always have to analyze implementation thoroughly and check it from various aspects. If I see localStorage in dependencies list, I know for the fact that I'm using HTML5 local storage to save some data. I don't have to look for it in the code.
Lifespan of components
We don't need to bother anymore about order of initialization of certain components. If A is dependent on B then DI will make sure that B is ready when A needs it.
Unit testing
It helps a lot to mock out components when you are using DI. For instance, if you have controller: function Ctrl($scope, a, b, c, d) then you instantly know what it is dependent on. You inject proper mocks, and you are making sure that all parties talking and listening to your controller are isolated. If you have troubles writing tests then you most likely messed up levels of abstraction or are violating design principles (Law Of Diameter, Encapsulation, etc.)
Good habits
Yes, most likely you could use namespacing to properly manage the lifespan of your objects. Define singleton where its needed and make sure that noone messes up your private members.
But honestly, would you need that if the framework can do it for you?
I haven't been using JS "the right way" just until I learned Angular. It's not that I didn't care, I just didn't have to since I was using JS just for some tweeks of UI, primarly based on jquery.
Now its different, I got a nice framework which forces me a bit to keep up with good practices, but it also gives me great power to extend it and make use of the best features that JS has.
Of course poor programmers can still break even the best tool, but from what I've learned by recently reading "JS the good parts" by D. Crockford people were doing reeeeeealy nasty stuff with it. Thanks to great tools like jQuery, Angular and others we now have some nice tool which helps to write good JS applications and sticking to best practices while doing so.
Conclusion
As you have pointed out, you CAN write good JS applications by doing at least those three things:
Namespacing - this avoids adding stuff to global namespace, avoids potential conflicts and allows for resolving proper components easily where needed
Creating reusable components / modules - by, for instance, using function module pattern and explicitly declaring private and public members
Managing dependencies between components - by defining singletons, allowing for retrieving dependencies from some 'registry', disallowing of doing certain stuff when certain conditions are not meet
Angular simply does that by:
Having $injector which manages dependencies between components and retrieves them when needed
Forcing to use factory function which has both PRIVATE and PUBLIC APIs.
Let the components talk to each other either directly (by being dependent of one another) or by shared $scope chain.

What are the benefits of AngularJS dependency injection?

I have been working with Angular for some time now, and I fail to see how it is an improvement from my previous way of coding.
First, I can't see what's wrong with having a central object to hold your project. After all, the injector is a singleton that looks up your dependencies into a central place, so Angular does have a central object, it's just hidden. Namespacing doesn't necessarily mean coupling, if it's done properly. And even when it's done, you don't need every single object of your code to be loosely coupled with the others. Besides, anytime you create a standalone JS script, you have to wrap it into Angular to make them play nice together.
Second, it's very verbose to declare all your dependencies everytime (especially with minification), so there is no gain from the readability point of view compared to proper namespacing.
Third, the performance gain is minimal. It forces me to use singletons everywhere, but I can do that on my own if I need to, and most of the time, I don't (network and DOM manipulations are my bottleneck, not JS objects).
In the end, I like the "enhanced" HTML and the automatic two-way bindings, but I can't see how the injection makes it any better than the way other frameworks deal with dependencies, given that it doesn't even provide dynamic loading like require.js. I haven't see any use case where I say to myself "oh, this is where it's so much better than before, I see" while coding.
Could you explain to me what benefits this technical choice brings to a project?
I can see only one for now: convention and best practice enforcement. It's a big one to create a lib ecosystem, but for now I don't see the fruit of it in the Angular community.
For me there are few aspects of how Angular's dependency injection is improving my projects, which I will list here. I hope that this will show you how OTHERS can benefit from it, but if you are well organised and experienced JS developer, then perhaps it might not be the same case for you. I think at some point this is just the matter of developing your own tools and coding guide.
Unified, declarative dependency resolving
JS is dynamic language (that's new, huh?) which gives a lot of power and even more responsibility to the programmer. Components can interact with each other on various ways by passing around all sorts of objects: regular objects, singletons, functions, etc. They can even make use of blocks of code which were not even mentioned to be used by other components.
JS has never had (and most likely never will) a unified way of declaring public, private or package (module) scopes like other languages have (Java, C, C#). Of course there are ways of encapsulating logic, but ask any newcomer to the language and he will simply don't know how to use it.
What I like about DI (not only in Angular, but in general) is the fact that you can list dependencies to your component, and you are not troubled how this dependency got constructed. This is very important for me, especially that DI in Angular allows you to resolve both kinds of components: these from the framework itself (like $http), or custom ones (like my favorite eventBus which I'm using to wrap $on event handlers).
Very often I look at the declaration of a service and I know what it does and how it does it just by looking at dependencies!
If I was to construct and/or make use of all those objects deep in the component itself, then I would always have to analyze implementation thoroughly and check it from various aspects. If I see localStorage in dependencies list, I know for the fact that I'm using HTML5 local storage to save some data. I don't have to look for it in the code.
Lifespan of components
We don't need to bother anymore about order of initialization of certain components. If A is dependent on B then DI will make sure that B is ready when A needs it.
Unit testing
It helps a lot to mock out components when you are using DI. For instance, if you have controller: function Ctrl($scope, a, b, c, d) then you instantly know what it is dependent on. You inject proper mocks, and you are making sure that all parties talking and listening to your controller are isolated. If you have troubles writing tests then you most likely messed up levels of abstraction or are violating design principles (Law Of Diameter, Encapsulation, etc.)
Good habits
Yes, most likely you could use namespacing to properly manage the lifespan of your objects. Define singleton where its needed and make sure that noone messes up your private members.
But honestly, would you need that if the framework can do it for you?
I haven't been using JS "the right way" just until I learned Angular. It's not that I didn't care, I just didn't have to since I was using JS just for some tweeks of UI, primarly based on jquery.
Now its different, I got a nice framework which forces me a bit to keep up with good practices, but it also gives me great power to extend it and make use of the best features that JS has.
Of course poor programmers can still break even the best tool, but from what I've learned by recently reading "JS the good parts" by D. Crockford people were doing reeeeeealy nasty stuff with it. Thanks to great tools like jQuery, Angular and others we now have some nice tool which helps to write good JS applications and sticking to best practices while doing so.
Conclusion
As you have pointed out, you CAN write good JS applications by doing at least those three things:
Namespacing - this avoids adding stuff to global namespace, avoids potential conflicts and allows for resolving proper components easily where needed
Creating reusable components / modules - by, for instance, using function module pattern and explicitly declaring private and public members
Managing dependencies between components - by defining singletons, allowing for retrieving dependencies from some 'registry', disallowing of doing certain stuff when certain conditions are not meet
Angular simply does that by:
Having $injector which manages dependencies between components and retrieves them when needed
Forcing to use factory function which has both PRIVATE and PUBLIC APIs.
Let the components talk to each other either directly (by being dependent of one another) or by shared $scope chain.

Has inheritance become bad?

Personally, I think inheritance is a great tool, that, when applied reasonably, can greatly simplify code.
However, I seems to me that many modern tools dislike inheritance. Let's take a simple example: Serialize a class to XML. As soon as inheritance is involved, this can easily turn into a mess. Especially if you're trying to serialize a derived class using the base class serializer.
Sure, we can work around that. Something like a KnownType attribute and stuff. Besides being an itch in your code that you have to remember to update every time you add a derived class, that fails, too, if you receive a class from outside your scope that was not known at compile time. (Okay, in some cases you can still work around that, for instance using the NetDataContract serializer in .NET. Surely a certain advancement.)
In any case, the basic principle still exists: Serialization and inheritance don't mix well. Considering the huge list of programming strategies that became possible and even common in the past decade, I feel tempted to say that inheritance should be avoided in areas that relate to serialization (in particular remoting and databases).
Does that make sense? Or am messing things up? How do you handle inheritance and serialization?
There are indeed a few gotcha with inheritance and serialization. One is that it leads to an asymmetry between serialization/deserialization. If a class is subclassed, this will work transparently during serialization, but will fail during deserialization, unless the deserialization is made aware of the new class. That's why we have tags such as #SeeAlso to annotate data for XML serialization.
These problems are however not new about inheritance. It's frequently discussed under the terminology open/closed world. Either you consider you know the whole world and classes, or you might be in a case where new classes are added by third-parties. In a closed world assumption, serialization isn't much a problem. It's more problematic in an open world assumption.
But inheritance and the open world assumption have anyway other gotchas. E.g. if you remove a protected method in your classes and refactor accordingly, how can you ensure that there isn't a third party class that was using it? In an open world, the public and internal API of your classes must be considered as frozen once made available to other. And you must take great care to evolve the system.
There are other more technical internal details of how serialization works that can be surprising. That's for Java, but I'm pretty sure .NET has similarities. E.g. Serialization Killer, by Gilad Bracha, or Serialization and security manager bug exploit.
I ran into this on my current project and this might not be the best way, but I created a service layer of sorts for it and its own classes. I think it came out being named ObjectToSerialized translator and a couple of interfaces. Typically this was a one to one (the "object" and "serialized" had the exact same properties) so adding something to the interface would let you know "hey, add this over here too".
I want to say I had a IToSerialized interface with a simple method on it for generic purposes and used automapper for most of the conversions. Sure, it's a bit more code but hey whatever, it worked and doesn't gum up other things.

Creating Core Foundation classes

Since I can't seem to find any documentation on this subject, is it possible to create your own Core Foundation "class"? (classes as in ones that can be used with CFRetain() and CFRelease) I want to take advantage of the polymorphic capabilities and object inspection built into Core Foundation without the overhead of Objective-C or creating my own object hierarchy.
Be forewarned: I believe that Core Foundation doesn't have true inheritance without Objective-C loaded, and with Objective-C loaded you'll get the (minor) associated slowdowns anyway.
There probably won't be any documentation on it, but it might be possible. It certainly won't be clean. Try browsing through the CF-Lite source code (link is for Mac OS X 10.5.7) to get a feel for the framework's implementation.
Note that if the overhead of Objective-C you mention is the overhead of message invocation, there are a great many ways to optimize it (for example, the -instanceMethodForSelector: method). You're very likely to spend more time trying to worm your way into the Core Foundation framework than you are trying to optimize Objective-C code to bring it up to speed.
Technically, there are no Core Foundation classes. They are opaque types.

Is ActiveRecord bad practice?

I'm starting a new project and i've recently found castle project activerecord, which seems like a GREAT solution, but at the same time, it looks like something realy unconventional.
I was wondering, does this feeling comes from learning something new (and i should just get used to it) or is really bad practice?
Part of what felt weird to me about using ActiveRecord was having to inherit from ActiveRecordBase<T>, and having all those persistence methods on your object (Save and so forth).
But it turns out you don't have to! Instead of having, say:
[ActiveRecord]
class Customer : ActiveRecordBase<Customer> { }
You can just have
[ActiveRecord]
class Customer : inherit from whatever you want { }
and then use ActiveRecordMediator<Customer>. It has basically the same static methods that ActiveRecordBase<T> has, but this way you don't have to clutter your object model with them. If you don't need the various protected method event hooks in ActiveRecordBase<T>, this can make things simpler.
ActiveRecord is a design pattern first named by Martin Fowler in Patterns of Enterprise Application Architectures. It is fairly common and used extensively in the popular Ruby framework Rails.
It contrasts with the more usual style of development in the .Net world which is to use DAOs, and that perhaps explains why you're uneasy.
A suggestion: read the source code for some Ruby on Rails applications which are similar to your own projects, and evaluate how you like the design style that results from heavy use of ActiveRecord.
It's not a bad solution but it has it's downsides.
In Patterns of Enterprise Application Architecture Martin Fowler describes several ways of designing applications that are built on top of a database. These methods differ in the way the application is decoupled from the database. He also describes that more decoupling makes more complex applications possible. Active Record is described as a way to design simpler applications but for applications with more complex behaviour you need a Domain Model that is independent of the database and something like an object-relational mapper in between.
ActiveRecord works very well in Ruby, but it's not easily transferable to all languages. The central feat of AR is the metaphor of table=class, row=instance. This comes out quite elegant in Ruby, because classes are also objects. In other languages, classes are usually a special kind of construct, and then you have to go through all sorts of hoops to make it work like properly. This takes away some of the natural feel that it has in Ruby.
The mixture of the domain object with the service layer is the biggest bad practice (if you see that as a bad practice). You end up calling user.Save() which means if you want to change your ORM, you are reliant on this pattern. The 2 alternatives are a layer aka a set of facade classes to perform your CRUD operations, or to put this inside the domain object as something like
User.Service.Save(user);
If you're using .NET then ActiveRecord is obviously ActiveRecord based, Coolstorage, Subsonic and a few others.
No it's not bad practice. Even in .NET it's a fairly well established pattern now. SubSonic (http://subsonicproject.com) and LINQ to SQL also use the pattern.
Implementations of the pattern, such as Subsonic, are great for quickly and easily creating a data access layer that manages the CRUD for your application.
That doesn't mean it's a good solution for all systems. For large, complex systems you probably want to have less coupling to the data store.
I think ActiveRecord has not much to do with Castle and therefore, the answers to this question Does the ActiveRecord pattern follow/encourage the SOLID design principles? could be more enlightening to many.

Resources