5

I have found some blog where there is a suggestion of avoiding new keyword while creating object of a class. Some examples of creating object without the new keyword are-

SampleObject obj = Class.forName("com.example.SampleObject").newInstance();

Or using clone() method -

SampleObject obj1 = new SampleObject();  
SampleObject obj2 = obj.clone();

Then here I have found some good examples of creating object without new keyword

I can understand the advantages of 'Factory' pattern while avoiding new keyword from main portion of code. If I am not using any design pattern (for creating objects) is there any benefit of creating object without the new keyword? Or what are the reasons for creating of object without new?

Community
  • 1
  • 1
Razib
  • 10,965
  • 11
  • 53
  • 80
  • I think, it's all about `static` method for creating objects. Something like `Paths.get` for standard library. – Dmitry Ginzburg Dec 19 '14 at 11:56
  • Then how are you planning to create object? Aren't you going to pass string to create object that you would use to load your class? – SMA Dec 19 '14 at 12:03

5 Answers5

9

What you read in the blog must have been about factory methods and similar techniques, which don't avoid new, but rather place it behind a more flexible API.

There are definetely no overarching downsides to the new operator. It has been, and will remain, the staple of any Java code, and the most natural way to actually create an object, as opposed to satisfying a more generic concern, such as "provide me with an entry point to your API".

All other techniques that create objects without involving new are special-purpose tools (cloning, deserialization, etc.).

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • The other techniques must be *less efficient* right?. I mean under the hood, they must all be doing what *new* does internally. I was going through the java source code of `newInstance0()`, there is a lot of code in there :). Does any other techninque provide better performance than `new`? – TheLostMind Dec 19 '14 at 12:47
  • Since `new` is the target of the most aggressive optimizations by the runtime, including Escape Analysis with the prospect of not allocating the object at all, it is basically impossible to get more efficient than `new`. As always, use standard idioms and enjoy the benefits of the optimizing monster that HotSpot has become. – Marko Topolnik Dec 19 '14 at 12:49
  • Actually, you could get more efficient than new...by pooling instances. – Andres Dec 19 '14 at 13:23
  • @Andres The context is "more efficient at *creating* instances". – Marko Topolnik Dec 19 '14 at 13:24
  • Yeah, agree. However, I think that stating that "there are definetely no overarching downsides to the new operator", is a bit misleading. I've seen many problems resolved only by replacing new by something different (singletons, DI, pooling, etc.) – Andres Dec 19 '14 at 13:27
  • @Andres Ripped out of context, any statement is misleading. This question is *about* object creation, and my answer reiterates that. – Marko Topolnik Dec 19 '14 at 13:29
2

Complex Objects

In general you may consider avoiding new for reasonably complex objects with non-trivial creation. You can consider some factory/builder which add versatility.

For example if you create a big composite object it is good to use builder pattern. (Long example here)

Simple Objects

For simple objects (most common case) it is best to stick with new.

For example if you have simple class

public class Dog{
    private string name;

    //getter + setter
}

Then it is an overkill to create factory for this and you should call it by new Dog()

Dependency Injection

In enterprise applications you commonly use dependency injection, which let's you avoid using new explicitly. You won't remove all object instantiations, but it provides nice improvement. (Basic Spring tutorial here)

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
1

When you use Class.forName, the class name can be set at runtime. That can be useful for drivers e.g.

When you use new, instead, the class name of the instance you're creating is hard coded. In general, this creates high coupling, and should be avoided (Except when you're absolutely sure you'll always need this coupling).

In short, if you want to create an instance of a specific class, new makes no harm.

However, you should ask yourself:

  • If you really need a new instance (Otherwise, you should replace new by a singleton or a pool).
  • If you'll always use the same class for that instance (Otherwise, you should replace new by Dependency Injection or the Factory Pattern).
Andres
  • 10,561
  • 4
  • 45
  • 63
1

there is no replacement for new, even Class.forName("XYZ").newInstance() HAS to work exactly like new, the only difference being that you're hardcoding the full class (or even package...class) hence actually achieve the opposite of what you're trying to do, with new the instance may be dynamically resolved and/or even injected.

If you inject an instance of interface A you may very well get a bean of class B which implements A - thats in fact more dynamic and complements factory patterns very well. Thats hardly possible if your classname is hardcoded, at least in my humble opinion.

specializt
  • 1,913
  • 15
  • 26
  • 1
    When you use Class.forName, you don't have to hard code the class name. nor package. In fact, that's the main reason for using Class.forName. – Andres Dec 19 '14 at 13:20
-4

If you like sluggish, slow code, that is hard to debug, maintain and understand, absolutely, avoid using new keyword at all costs, obfuscate as much as possible!

Dima
  • 39,570
  • 6
  • 44
  • 70
  • 3
    shhhh! Dont you spread thruth on all the young "programmers" and "hackers" out there! They dont like that! – specializt Dec 19 '14 at 12:23
  • For creation of objects which require external resources, more subcomponents your "not obfuscated" code will take 20 lines in every place when object is created. It's better to have these 20 lines in single place and not to repeat them all the time. – Marcin Szymczak Dec 19 '14 at 12:24
  • 1
    of course - but that wont remove the need for `new` in your factory . – specializt Dec 19 '14 at 12:25
  • @MarcinSzymczak, huh? Put the 20 lines where you want ... What are you talking about? – Dima Dec 19 '14 at 14:21