Builder vs Factory Method pattern - factory-method

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.

Related

Services vs Factory in agularJs

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

Is there non static function in Elixir?

I am newbie in Elixir, coming from java background. I saw Elixir's function as static methods in java. So I wonder, is there any non-static method / function in Elixir?
Thank you
Nope - all functions belong to a module. Elixir is not an class-oriented language, so the concept of "instance methods vs. class methods" is not applicable.
Aside from typical named functions which belong to a module, there are anonymous functions, similar to lambdas in Java.
The accepted answer is correct and I upvoted it. The basic building blocks in OOP are objects. On the BEAM (Erlang VM), the basic building blocks are processes. So, the distinction between static/instance methods just doesn't make sense.
However, when thinking about what instance methods do in an object oriented language, there is something that does a similar thing in Elixir.
Instance methods, when contrasted with class methods, are the ones that work with internal object state. Elixir doesn't have classes or objects, but it does have processes. A GenServer process instance maintains state and passes it into each callback function. So, when you're looking for something that will have state and functions to modify it or return some piece of it, then you want to reach for a GenServer in Elixir.
All the functions will still belong to the Module. They aren't a unique type of function, but they do allow you to manipulate the state of a given instance of the process because the state gets passed in as a parameter and returned within the function's result.
In response to the comment by #ibgib, yes, when compared with an object oriented language like Java or C#, you can think of all modules and functions in Elixir/Erlang as being static. This is comparing apples to oranges, but if it helps when learning to think of them that way, I think that's OK. Just realize that there isn't any such thing as instance methods here.

Data Contract Serializer mandates super class to know about subclass

I got this problem,
"The deserializer has no knowlege of any type that maps to this contract"
After googling, I reached this post
The deserializer has no knowlege of any type that maps to this contract
where the answer says, the base class have to declare "KnownTypes" like
[DataContract, KnownType(typeof(Subclass)) ...],
If I have to declare this in my parent class, [DataContract, KnownType(typeof(Subclass))], doesn't it break the principles of OO Design that parent class doesn't have to know about subclass?
What is the right way of doing this?
The serializer is designed in a way that, if it serializes an object, it should be able to read it back. If you attempt to serialize an object with a declared type of 'Base', but an actual type of 'Derived' (see example below), if you want to be able to read back from the serialized object an instance of 'Derived', you need to somehow annotate the XML that the instance is not of the type of which it was declared.
[DataContract]
public class MyType
{
[DataMember]
public object obj = new Derived();
}
The serialized version of the type would look something like the XML below:
<MyType>
<obj actualType="Derived">
<!-- fields of the derived type -->
</obj>
</MyType>
When the type is being deserialized, the serializer will look at the "actualType" (not actual name) attribute, and it will have to find that type, initialize it, and set its properties. It's a potential security issue to let the serializer (with in Silverlight lives is a trusted assembly and has more "rights" than the normal user code) to create arbitrary type, so that's one reason for limiting the types which can be deserialized. And based on the design of the serializer (if we can serialize it, we should be able to deserialize it), the serialization fails for that reason as well.
Another problem with that is that the serialized data is often used to communicate between different services, in different computers, and possibly with different languages. It's possible (and often it is the case) that you have a class in a namespace in the client which has a similar data contract to a class in the server side, but they have different names and / or reside in different namespaces. So simply adding the CLR type name in the "actualType" attribute won't work in this scenario either (the [KnownType] attribute helps the serialzier map the data contract name / namespace to the actual CLR type). Also, if you're talking to a service in a different language / platform (i.e., Java), CLR type names don't even make sense.
Another more detailed explanation is given at the post http://www.dotnetconsult.co.uk/weblog2/PermaLink,guid,a3775eb1-b441-43ad-b9f1-e4aaba404235.aspx - it talks about [ServiceKnownType] instead of [KnownType], but the principles are the same.
Finally, about your question: does it break that OO principle? Yes, that principle is broken, that's a price to pay for being able to have lose coupling between the client and services in your distributed (service-oriented) application.
Yes it breaks the principles of OO design. This is because SOA is about sharing contracts (the C in ABC of services) and not types, whereas OO is about type hierarchies. Think like this the client for a service may not be even in an OO language but SOA principles can still be applied. How the mapping is done on server side is an implementation issue.

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