samedi 28 juillet 2018

Java: reusing same Object variable to create multiple objects

First off, some pseudo code:

//case 1:
main {
    List<Foo> bar = new ArrayList;

    Foo baz = new Foo(params);
    Foo baz1 = new Foo(differentParams);
    Foo baz2... 
}

Foo {
    main.bar.add(this);
}

//case 2:
main {
    List<Foo> bar = new ArrayList;

    Foo baz = new Foo(params);
    baz = new Foo(differentParams);
    baz = new Foo..
}

Foo {
    main.bar.add(this);
}

I am wondering if case 2 is an okay design practice. Since in Foo I am storing the instance of the class in the list in main, I will never need the direct object variable baz1 during runtime, but will be iterating through the list to apply some logic to each object. So my question is, is it an alright practice to reuse the same variable to keep making new Object instances (like case 2)? Conventional practices would suggest to keep a separate variable for the objects as you make them (like case 1).

This question came up in my mind when thinking about memory and whether or not doing case 2 would save more memory compared to case 1 since you are not declaring a new variable each time.

Aucun commentaire:

Enregistrer un commentaire