Java Best Practices – Is It Bad Practice to Create New Objects Without Storing Them?

java

I've seen objects created in Java code without storing a reference to the object. For example, in an eclipse plugin I've seen a SWT Shell created like so:

new Shell();

This new Shell object is not stored in a variable, but will remain referenced until the window is disposed which [I believe?] happens by default when the window is closed.

Is it bad practice to create objects like this without storing a reference to them? Or was the library poorly designed? What if I don't have need of a reference, but only want the "side effects" of the object? Should I store a reference anyways?

UPDATE:

Admitedly, my above example is poor. While I have seen UI elements created like this, creating a SWT Shell like this would probably be pointless because you need to call the open method on the Shell instance. There are better examples provided by aix such as the following from the Java concurrency tutorial:

(new HelloThread()).start();

This practice is seen in many contexts, so the questions remains. Is it good practice?

Best Answer

There's an element of personal preference to this, but I think that not storing the reference is not necessarily a bad practice.

Consider the following hypothetical example:

new SingleFileProcessor().process(file);

If a new processor object needs to be created for every file, and is not needed after the process() call, there's no point in storing a reference to it.

Here is another example, taken from the Java concurrency tutorial:

(new HelloThread()).start();

I've seen lots of other examples when the reference is not stored, and that read perfectly fine to my eye, such as:

String str = new StringBuilder().append(x).append(y).append(z).toString();

(The StringBuilder object is not kept.)

There are similar patterns involving common.lang's HashCodeBuilder et al.

Related Topic