- one for starting the application (1)
- one for connecting to the database (2)
- one with getter- and setter-methods to work on a table in the connected database (3)
They are organized in the same package.
Where would I create instances of (2) and (3)? Would (1) be the right place to do so?
That means: should all instances generally be created in a starting class?
What are the pro' s and con' s to do this?
Or does it depend on the application itself which way' s the best to choose?
Generally, you would create the object when you need it.
The idea is to make your code as clean and simple as possible. You spend a LOT of time looking at old code, and you want to make it as easy as you can for your future self (or others) to understand what you are doing. Creating an object you don't use until way, way, way later can be very confusing.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Feb 06, 2013
I' ll rewrite my code based on your explanation.
Thanks for your help!
There is a catch, though.
Following this approach in the example you provided might lead to (3) creating an instance of (2) to establish a connection to the database when you need to access a table.
It might well be better to have (1) create the instance of (2) and pass it to an instance of (3). That way you could keep track of a pool of database connections, or it would allow you to easily swap out an instance of (2) for a test double in a unit test.
This is called dependency injection and it directly impacts the responsibility of object creation.
Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
The question is a very good one, and it touches one of the very topics of Java (or common OO) architecture. At the time when you are getting deeper into Java programming you will probably get used to principles and paradigms dealing with situations where you can do it "this or that way".