0

Say I have the code:

    class Foobar {
        Object item = null;
        ItemInstantiator inst = new ItemInstantiator();
        public instantiateItem() {
            inst.instantiate(item);
        }
    }

    class ItemInstantiator {
        public instantiate(Object item) {
            item = new Object();
        }
    }

Since the Foobar class has a live reference to the new object created in instantiate(), that new object should not be garbage collected after instantiate() finishes, right?

I ask because I am working on a project where it makes the most sense to declare an object in one class and instantiate the object in the method of another class. The problem is, once the instantiation finishes, the object is still null.

  • 1
    Java is pass-by-value, so you cannot modify the value of the `item` argument, as you are attempting to do. If `item` contained a non-null reference to some object, you could modify that object if it was mutable, but you cannot affect the value of `item` in `Foobar` from within `ItemInstantiator#instantiate()`. If this seems unclear, read http://stackoverflow.com/q/40480/18157. This has nothing to do with object lifetimes. You created a new object and immediately discarded it. – Jim Garrison Mar 10 '16 at 07:43

1 Answers1

2

You are instantiating the object in the method and NOT returning its reference

You should change to

class Foobar {
        Object item = null;
        ItemInstantiator inst = new ItemInstantiator();
        public instantiateItem() {
           item = inst.instantiate(item);
        }
    }

    class ItemInstantiator {
        public Object  instantiate(Object item) {
            item = new Object();
            return item;
        }
    }

The Book Clean Code - A Handbook of Agile Software Craftmanship states that, in general output arguments should be avoided. If your function must change the state of something, have it change the state of its owning object.

Please rethink the class design, whether it really makes sense to instantiate the object by Passing reference. As per your code, it doesn't make any sense. You can just do the object creation without passing any argument item

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
  • Thank you for the well-formed response. The reason I am doing this is to create a linked list type structure recursively by instantiating a list element, assigning to it the previous element's pointer, and then passing the new element's pointer so that it may be assigned on the next recursion. Also I have been using return statements for error codes. – Gary Dunn Mar 10 '16 at 08:23
  • ok, you should choose to do that in a single class. That would be more specific in function. Also, Try to use exception handling instead of error codes. It would make your code more complex. That's just my view. – Keerthivasan Mar 10 '16 at 09:13