Services vs Factory in agularJs - angularjs

Is there any thing exist which I could do in service but not in factory or vice-versa? Basically I want to conclude the difference between the service and a factory.

you can take a look at a the new post .service() versus .factory(), the actual answer. by #ToddMotto
So, what is a service?
A Service is just a function for the business layer of the application, it’s just a simple function. It acts as a constructor function and is invoked once at runtime with new, much like you would with plain JavaScript
Factory
Next, the confusing .factory() method. A factory is not just “another way” for doing services, anyone that tells you that is wrong. It can however, give you the same capabilities of a .service(), but is much more powerful and flexible.
A factory is not just a “way” of returning something, a factory is in fact a design pattern. Factories create Objects, that’s it. Now ask yourself: what type of Object do I want? With .factory(), we can create various Objects, such as new Class instances (with .prototype or ES2015 Classes), return Object literals, return functions and closures, or even just return a simply String. You can create whatever you like, that’s the rule.
Enjoy

Related

In terms of angular should i assign functions to services and app wide variables to factories?

So let's say I have the following:
factory
var currentRecordId
controller
$scope.currentRecord = MyService.getCurrentRecordById(MyFactory.currentRecordId)
service
//define getCurrentRecordById
My thinking is that the factory holds all variables (and therefore state) that I need across multiple controllers and my service holds functions which I will need across multiple controllers.
The reasoning being that functions in factories will compute the function once and return the value where as a service will call the function.
Is this an expected way of going about placing common variables and common functions in a angular app or is there a better way.
I do not want to place functions or variables in the rootscope because I do not need these functions and variables for every controller only a subset.
Actually, as few resources state it over the internet (here, for instance), there is very few differences (not to say only One) between factories and services. And those differences are implementation differences, AngularJS design choices. For the developers using the framework in an ES5 environment, this is the exact same thing.
So you don't need to split attributes and methods in factories and services. You can define ONE factory/service with a private attribute and define a public getter, or define both public (if you need the attribute as a "app wide variable").
Sharing data between controllers is a job suiting Services (/factories) perfectly.

angularjs using angular.extend to bind $scope to a service bad/good practice

I'd like to know if using
angular.extend($scope,MyService);
Does it break oop encapsulation principle ?
Does it smell like MyService.call($scope) ?
Could you face variable and function conflicts ?
Is this a bad/good practice?
Typically from my experience services are injected into the controller and then will be called from that scope. I wouldn't say that using extend to copy over functions and properties is necessarily bad, but it might mitigate some of the purposes of IoC (inversion of control), which is what injection in angular is based on.
Does it break oop...?
My understanding is that what you would get from this call is additional functions and service calls directly on your scope. This doesn't break OOP in the sense that scope is an object and would have functions applied. Provided those functions + properties make sense on the scope it seems like a fine thing to do from that perspective.
Does it smell like MyService.call($scope)?
As I said in the first paragraph - I don't see why you wouldn't just call the service and either share data or pass in references to objects to the service. Another pattern that is common in angular is to use a promise to process returned data in your scope. That looks like:
MyService.callFunction(parameters).then(function (data) {
// process data here. Since this runs in $scope you can also use $scope normally.
// $scope.$apply() is in progress and will complete when the function returns
});
All the service does is provide the data to the scope then. Point is that I think there are better patterns than "extend".
Can you face conflicts?
In the call angular.extend(a, b); data, properties and functions are copied from b to a. If something already exists on a it will be overwritten with the data from b. So technically the short answer is "yes", you can face conflicts.
The bottom line
So at the end of the day this isn't a bad pattern but there are probably more common patterns I would try to use first.

Builder vs Factory Method pattern

I was reading about Builder pattern and as usual I got confused with Factory pattern.
I have seen a good article which shows the difference between Abstract Factory and Builder pattern.
http://champika-nirosh.blogspot.in/2008/04/what-is-difference-between-abstract.html
But my confusion is that, more than Builder pattern similar to Abstract Factory I feel like it is similar to Factory Method pattern. Not sure my understanding is correct. But in Factory Method also we are using a separate factory (Method in Concrete Factory) to create one particular object (not a family of product). In that scenario how Builder differs from Factory Method pattern. I knew that Builder requires more steps to create object, other than that is there any particular scenario we need to use one over another? Please guide me.
Thanks.
Your particular usage case will affect which (if either) you might choose. But to essentially reiterate what's on the link you reference:
Both abstract factory and factory method are creating instances of unknown types. Generally these will be returning a class that corresponds to an interface, but you don't know (and shouldn't care) what the concrete type will be. To use the picture from that link, it's using a WindowsFactory, meaning the abstract factory is returning an instance that is compatible with Windows. If your factory were instead a LinuxFactory, you might get an object back that works on Linux. Note, also, that you probably wouldn't know if you had a LinuxFactory or WindowsFactory, just that you had a Factory of a particular type.
So the abstract factory & factory method patterns are about building polymorphic types (including when you don't know or care what the concrete type will be). However, the call to get an instance of the type is usually trivial. To build from a factory you're probably just calling:
MyInterfaceType myInstance = myFactory.getTheItemOfMyInterfaceType();
The builder pattern is more about building complex objects that may or may not be (but probably are) of a known type. In this case you'd expect a complex series of calls to construct the type, often setting one parameter after another. Because there's a lot of known parameters and arguments, you generally know what type of object you're going to get back from it (don't have to, but it's more likely than with an abstract factory). Builder is used when constructing the object is complex, but not necessarily polymorphic (it might be polymorphic, but that's not the premise of the pattern). A builder call to construct something might be (see Android AlertDialog for some real examples):
Builder b = new Builder();
b.setSomeValueA(myChoiceForA);
b.setSomeValueB(myChoiceForB);
MyInterfaceType myInstance = b.build();
Hope that helps.

Can a Mock framework do this for me?

I am a bit confused
from wiki:
"This means that a true mock... performing tests on the data passed into the method calls as arguments."
I never used unit testing or mock framework. I thought unit tests are for automated tests so what are mock tests for?
What I want is a object replacing my database I might use later but still dont know what database or orm tool I use.
When I do my programm with mocks could I easily replace them with POCO`s later to make entity framework for example working pretty fast?
edit: I do not want to use unit testing but using Mocks as a full replacement for entities + database would be nice.
Yes, I think you are a bit confused.
Mock frameworks are for creating "Mock" objects which basically fake part of the functionality of your real objects so you can pass them to methods during tests, without having to go to the trouble of creating the real object for testing.
Lets run through a quick example
Say you have a 'Save()' method that takes a 'Doc' object, and returns a 'boolean' success flag
public bool Save(Doc docToSave(){...}
Now if you want to write a unit test for this method, you are going to have to first create a document object, and populate it with appropriate data before you can test the 'Save()' method. This requires more work than you really want to do.
Instead, it is possible to use a Mocking framework to create a mock 'Doc' object for you.
Syntax various between frameworks, but in pseudo-code you would write something like this:
CreateMock of type Doc
SetReturnValue for method Doc.data = "some test data"
The mocking framework will create a dummy mock object of type Doc that correctly returns "some test data" when it's '.data' property is called.
You can then use this dummy object to test your save method:
public void MyTest()
{
...
bool isSuccess = someClass.Save(dummyDoc);
...
}
The mocking framework ensures that when your 'Save()' method accesses the properties on the dummyDoc object, the correct data is returned, and the save can happen naturally.
This is a slightly contrived example, and in such a simple case it would probably be just as easy to create a real Doc object, but often in a complex bit software it might be much harder to create the object because it has dependencies on other things, or it has requirements for other things to be created first. Mocking removes some of that extra overload and allows you to test just the specific method that you are trying to test and not worry about the intricacies of the Doc class as well.
Mock tests are simply unit tests using mocked objects as opposed to real ones. Mocked objects are not really used as part of actual production code.
If you want something that will take the place of your database classes so you can change your mind later, you need to write interfaces or abstract classes to provide the methods you require to match your save/load semantics, then you can fill out several full implementations depending on what storage types you choose.
I think what you're looking for is the Repository Pattern. That link is for NHibernate, but the general pattern should work for Entity Framework as well. Searching for that, I found Implementing Repository Pattern With Entity Framework.
This abstracts the details of the actual O/RM behind an interface (or set of interfaces).
(I'm no expert on repositories, so please post better explanations/links if anyone has them.)
You could then use a mocking (isolation) framework or hand-code fakes/stubs during initial development prior to deciding on an O/RM.
Unit testing is where you'll realize the full benefits. You can then test classes that depend on repository interfaces by supplying mock or stub repositories. You won't need to set up an actual database for these tests, and they will execute very quickly. Tests pay for themselves over and over, and the quality of your code will increase.

Should a factory method of a custom container return the newly created instance?

I have a custom collection Doohickeys indexed by keys. This collection has a factory method createDoohickey(key) and an accessor Doohickey(key). Should createDoohickey(key) return the new object or should it return void?
In the first case, I would use it like this
myDoohickey = doohickeys.createDoohickey(key);
doStuff(myDoohickey);
in the other case like this
doohickeys.createDoohickey(key);
doStuff(doohickeys(key));
Which one would you consider preferable, and why?
EDIT I believe I have learned quite a bit over the years and that the answer I accepted is actually not really the best one.
I'm not sure the container should have a factory method to create the object it contains - good separation of concerns would be to separate object creation from the container.
Therefore, I think you should have something like this:
Doohickey myDookickey = new Doohickey();
doohickys.Add(key, myDookickey);
doStuff(myDookickey); // or
doStuff(doohickeys(key));
You are then free to use a separate object factory or instantiate Doohickey directly. This makes it easier to unit test the container with mock Doohickey objects.
If you must have the factory method, I would return the Doohickey, because it is probably cheaper to ignore the return value (assuming a reference/pointer is returned) when it is not needed than to use the index to retrieve it when it is.
Yes, a Factory should return the newly created instance.
However like Alex pointed out you could seperate the Repository and the Factory. I would most likely design the factory to have a reference to the repository. I don't think it would be the end of the world of you combined the two into one class just as long as the factory method actually returns the newly created instance.
The example above embeds the factory method in the container class. I agree with willcodejavaforfood, and this may or may not be a good idea over the longer term. The issue is whether the reduced coupling of splitting the factory into its own class is worth the extra cost.
As far as why a factory method should return the newly created instance, it is preferable to decouple creation from containment. Some users of the class might want one but not the other. Also, when you couple creation and containment you can no longer (unit) test creation without also testing containment.
This answer is from a colleague of mine. He suggested to have createDoohickey(key) indeed return the Doohickey; and, additionally, to call it getDoohickey(key) instead.
EDIT I believe after what I have learnt since that this answer is not necessarily the best one any more.

Resources