Martin Frøhlich Martin Frøhlich - 5 months ago 6
Java Question

Is chaining method calls to constructors a good practice in Java?

I have always thought that I have to initialize a class, before I can call it's non-static method, however, I came across a solution which had a method like this in it:

public String someStringMethod(){
return new MyClass().toString();

So I may be new in development, but is it a good practice? Is this a better way to call a method than the "classic" (see below) way?

public String classicStringMethod(){
MyClass cl = new MyClass();
return cl.toString();

Do they have any performance difference? Does the first way has a "special name"?


No significant difference

As the comments explained, both approaches are semantically the same.

The second approach assigns the new object to a reference variable. The first approach skips the use of a reference variable. But in both cases the class was used as a definition for instantiating an object, and then the toString method was called on that object.

Keep in mind that the variable is not the object. For example, the line Dog hershey = new Dog( "Australian Shepard" , "red", "Hershey" ); uses two chunks of memory. In one chunk is the new object, holding the state data for the breed and color and name. In the other separate chunk is the reference variable hershey holding a pointer to the memory location of the memory chunk of the Dog object. The reference variable lets us later refer to the object.

Java syntax makes this jump from reference variable to object so seamlessly that we usually think of hershey as the Dog object “Hershey”, but in fact they are separate and distinct.

I agree with the commentator muglio that the second approach is more clear in most cases. Plus it makes debugging easier, so your debugger can inspect the instantiated object by accessing the object via the reference variable.

As for performance, any difference would be insignificant. Indeed, the compiler or JVM may well collapse the second approach’s two lines into the first approach‘s single line. I don't know for sure, and I don't really care. Neither should you. Our job is to write clear readable code. The job of the compiler and JVM is to run that code reliably, efficiently, and fast. Attempting micro-optimizations has been shown many times to be futile (or even counter-productive) as the JVM implementations are extremely sophisticated pieces of software engineering, highly-tuned for making such optimizations. You can best assist the compilers and JVMs by writing simple straight-forward code without “cleverness”.