Search code examples
oopd

What is the difference between creation of instance and passing it as parameters and creation instance inside parameters?


What is the principal difference between next to records:

Database database = new Database(config);
User user = new User(database);

and

User user = new User(new Database(config));

Am I right understand that second one is just short form of first and can be used when I do not plan to call any database methods?


Solution

  • For most purposes there really isn't much difference. There are a couple of differences though:

    1. In the first case, you can access that Database instance via the database variable, whereas in the second, you would have to get it from the User instance that user references in order to do anything to it directly. That obviously doesn't matter if you're just constructing the User with the Database and then doing nothing with it directly.

    2. If the User instance that user references no longer has a reference to the Database object for some reason (e.g. it only used it in its constructor, or some other call made it set the member variable that was referring to it to null), and database still exists, then a reference to that Database object still exists in the program, and the GC can't collect it. That's mostly an issue if you're doing something like creating separate member variables for each object rather than using local variables or if you're passing the objects around individually, and if you're not going to be accessing the Database directly, then it really doesn't make sense to have a separate member variable for it or to pass it around.

    So, really, the only differences have to do with the consequences of having a separate reference to the Database, and if all you're doing with the Database is constructing the User, then having a database variable is completely unnecessary.