I'm a beginning programmer. I know the basics in OOP, but I don't know the "best practices" just yet. For instance, one paradigm that continues to come up in programming is the "Abstract Factory" design pattern, which seems fairly straightforward. One of the key intents behind it is to avoid the keyword "new", because it's considered harmful. I never heard this in the courses I took in programming. Could someone elaborate on that point? Why do we want to avoid instantiating objects in this form?
6 Answers
Consider in your client / caller class you write:
Vehicle v = new Car("BMW");
If your code is like the one above, you will always get a Car. In the future if you actually want a Plane, you will have to update the client code.
Alternatively, you use a factory pattern, you code something like:
Vehicle v = Factory.getVehicle();
Now you can keep the logic of getting the vehicle away (loose coupling) from the client and your client would never need a change in case you have to update the end vehicle you get. Only the Factory implementation will update and your clients will work as is.
-
2Very good response! Thank you; it does make sense when one considers the reusability of code. – Sal Dec 31 '11 at 22:10
-
1It's a good answer and you've obviously understood it but please also bear this in mind: very few of us work on frameworks. Most coding is in-house LOB application development that is extremely domain specific. The parts that are generic are usually ALREADY in a framework eg database access is provided by LINQ. There is a school of thought that says (when you are doing domain specific stuff rather than generic framework stuff) your code should be as simple and direct as possible. – Peter Wone Jan 01 '12 at 09:50
-
@Peter : I agree, Overdoing designing sometime tends to make the code complex. It definitely needs some consideration on how much coupling is OK in your application. But I still feel if you see you application growing in coming future, you should weigh the idea to keep it scalable/loosely coupled and that is where keeping a flexible design (in which design patterns may help) will help a lot. – Nrj Jan 01 '12 at 14:49
I wouldn't go so far to say that new
is considered harmful. What the abstract factory pattern attempts to do is solve the problem that new
is not overrideable (i.e. is not compatible with virtual dispatch, at least in languages like Java and C#).
Consider this sample code (C#):
class Sender
{
private ISendChannel channel;
public Sender()
{
}
public void Connect(Uri endpointAddress)
{
// !! Sender is tightly coupled to TCP implementation
// !! even though it doesn't apparently have to be.
this.channel = new TcpSendChannel(endpointAddress);
}
/* ... */
}
In this code, we have a base interface ISendChannel
to allow forward communication to some endpoint. However, the implementation as given is fixed to always use a TCP channel no matter what. This is not desirable because now if you want an HTTP sender, you either have to modify the Sender
class or add new methods to it. This is "bad coupling".
Instead, you could use a factory to create channels and pass it in to the sender. The sender will ask the factory to create the channel and thus give up that responsibility. The new implementation may look like this:
class Sender
{
private readonly ISendChannelFactory factory;
private ISendChannel channel;
public Sender(ISendChannelFactory factory)
{
this.factory = factory;
}
public void Connect(Uri endpointAddress)
{
// Sender does not have to care what type of channel it is.
this.channel = this.factory.CreateSendChannel(endpointAddress);
}
/* ... */
}
Now to use an HTTP channel, you could instantiate a sender using a different factory type, e.g. new Sender(new HttpSendChannelFactory(/* ... */));
. The HttpSendChannelFactory
could then return HttpSendChannel
(a concrete type deriving from ISendChannel
) from its CreateSendChannel
method.

- 23,769
- 3
- 56
- 67
I suggest reading this article: http://www.codinghorror.com/blog/2005/09/head-first-design-patterns.html
key part is: The best way to learn to write simple code is to write simple code! Patterns, like all forms of complexity, should be avoided until they are absolutely necessary. That's the first thing beginners need to learn. Not the last thing.
I agree with it - you need factory only when you really need it.
Ok, going back to topic, keyword new
can be evil, but in most of cases it surely isn't and shouldn't be source of headache. Seeing
List <Person> persons = new ArrayList<Person>();
Is perfectly fine. Don't even dare to think about factory producing ArrayList
or LinkedList
. That would be totally overengineered.
"I’ve seen numerous systems in which the Factory pattern was overused. For example, if every object in a system is created by using a Factory, instead of direct instantiation (e.g., new StringNode(ノ)),the system probably has an overabundance of Factories." @ Joshua Kerievsky
Don't add patterns premature unless you're sure that it's good idea, and you can't be sure of that without enough experience. Starting writing code with patterns in your mind - kind of: Factory, this is great, lets see when I can place it! - that's not a good idea :). Better would be adding patterns to places in your code that are troublesome, when you feel (smell :) - code smell) that this could be done somehow better. That is refactoring to patterns.
There is a great book about it, and I'll give you link to chapter "Move Creation Knowledge to Factory"
http://www.informit.com/articles/article.aspx?p=1398606&seqNum=2
I know it's long, but read it please, it's surely worth the effort

- 9,123
- 6
- 45
- 68
To understand this pattern or what is wrong with using the new
keyword you are missing an essential prerequisite programming paradigm which is Programming against an interface
Study this and once you understand what it is, you will understand that the only way to really enforce/follow it, is to avoid using new
in your code i.e. explicitely instantiating concrete objects in your code which has the nasty effect of code coupling.
-
Maybe I should read more on this specifically. I've heard that term get thrown around (code coupling), but I'm not understanding the what that term is trying to capture. Does it just refer to insufficient robusteness/reusability/etc.? – Sal Jan 01 '12 at 02:20
-
Coupling is tight or loose, loose being good. Basically it's a measure of how interdependent your code is. If you change X, how many other changes will your be forced to make that aren't directly dependent on X. In your question, with abstract factory any object taht satifies the interface will do, where a straight factory pattern, only that concrete class will do, so Abstract factory is more loosely coupled. – Tony Hopkinson Jan 02 '12 at 14:58
The idea of abstract factory pattern is not to know anything about the concrete implementation including constructors.
So a standard Factory pattern would return a concrete class e.g.
SomeType SomeVar = SomeFactory.CreateSomeType();
Where as abstract factory pattern would be
SomeInterface SomeVar = AbstractFactory.CreateSomeInterface();
So instead of SomeType being exposed to the consumer, only the interface is. Just a higher level of abstraction that's all, useful, but only harmful IF you don't want the factory consumer to have to know about SomeType.

- 20,172
- 3
- 31
- 39
Well as far as I know there is nothing wrong with new keyword. Im talking as PHP developer. There is nothing wrong with new keyword nor there are some secuity issues with it.
Factory pattern in PHP is used to automaticly require, make instance of class, and return that class. Not becuse there is something wrong with new keyword but becuse its much faster to run one static function then to require and use new keyword for every object you need.
And in the background you would anyway use new keyword :)
So nothing wrong with new and there is no need to avoid it. Its joust that with factory pattern its much faster to get class instance then to require class and then instanciate it with new keyword.

- 4,954
- 8
- 31
- 33
-
3It's not really a question of speed, but more about loose coupling and separation of responsibilities (separate the creation from the use of an object). – bobbymcr Dec 31 '11 at 22:00
-
So you're saying it's faster to call a factory method that uses "new" than it is to just use "new"? Do you have performance data that backs that up? – Dave Newton Jan 02 '12 at 05:23
-
No, im not saying is faster executed on the server. Im saying its easier to call $someClass = Factory::produce('someClass'); Its faster to use code like that and its easyer to manage objects creation using Factory. Thats what im saying but i didnt answerd the question anyway. The guy was looking for something else, my bad. – Limeni Jan 02 '12 at 11:47