简体   繁体   中英

Benefits of Avoiding 'new' Keword When Creating Object in Java

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 ?

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.).

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 )

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

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 ).

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.

如果您喜欢缓慢,缓慢的代码,这很难调试,维护和理解,绝对避免不惜一切代价使用new关键字,尽可能地混淆!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM