0

Is it ok if the program is written like this :

class ReduceCode 
{
    void display()
    {
        System.out.print("Hello");
    }
    public static void main(String[] X)
    {
        new ReduceCode().display();
    }
}

instead of

class ReduceCode 
{
    void display()
    {
        System.out.print("Hello");
    }
    public static void main(String[] X)
    {
        ReduceCode rc = new ReduceCode();
        rc.display();
    }
}

I understand the reason behind having to declare a reference to an object so that if there are any instance variables involved, in the future the value from those variables can be accessed using that reference, but for methods like display() which only prints something, the reference can be ignored.

Apart from this, does instantiation without reference have any disadvantage? I couldn't find any documentation on the official website. Is this technique used at industry level at all?

Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
  • 1
    I personally find the implicit discarding of the instance after use produces more readable code, as I know it to be the only relevant use of the instance. – Oli Mar 31 '15 at 08:17
  • There is no functional difference so it is only a matter of readability, which is subjective. – assylias Mar 31 '15 at 08:20
  • It is fine as long as it does not tempt to do tricks like using `{{ ... }}` [initialization](http://stackoverflow.com/questions/29363254/double-brace-initialization-and-serialization/29363359#29363359). – Joop Eggen Mar 31 '15 at 08:32

2 Answers2

1

The only disadvantage that I find is when debugging using breakpoints. In your second example, you can hover over the rc variable in Eclipse and inspect it.

But that's a small price to pay: the first way is much more readable and makes the scope of the object much clearer.

David Lavender
  • 8,021
  • 3
  • 35
  • 55
0

I know of no disadvantages to using objects as discardable tools in this way. I would actually suggest that it is better to use them this way if you don't need the instance reference.

The only time I can think of where this practice may be annoying is while debugging. You will not have an opportunity to inspect the details of the created object.

The new Streams system in Java 8 uses streams like this, they are often only in existence for a brief time while an expression is evaluating.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213