Java and mySQL, why create class objects with data from the database?

Viewed 394

So I have a homework assignment to build a console application in Java while utilizing mySQL databases. Our teacher wants us to use objects and ArrayLists, as Java is an "object oriented language".

I am not sure why I must parse the mySQL ResultSets into objects, and not print them directly in my methods in a nice printf format. Similarly, why should I make class objects when inserting new data and not altering the database directly through my connection.

Can someone please explain and point me in the right direction. I don't need any code. Just trying to understand.

2 Answers

One printf method for a ResultSet is not the correct way to implement! A resultset can have a different amount of different types of data.

The correct way would be to parse them to an object. For each table you might have an own class with constructor. For example:

You have a table 'Person' with attributes Name, age, address. Then you create a constructor

public Person(String name, int age, String address){}

or you could create a static method to parse like this:

public static Person parseFromResultSet(ResultSet r) throws ParseException {}

and then you can even write your own 'PersonParseExcpetion'.

"I am not sure why I must parse the mySQL ResultSets into objects, and not print them directly in a nice printf format. Similarly, why should I make class objects when inserting new data and not altering the database directly through my connection."

...mostly because in a real-world application you're likely to do a lot more with the records than just print them directly to the console, and at that point it's useful to put them into a solid data structure you can move around and manipulate easily.

It can also make the code easier to maintain - real-world apps get updated and altered lots of times usually, and may contain a lot of different data types and structures, some of which may be complex representations consisting of several other structures put together - and it's easier to build a complex object if you already have a lot of smaller objects to make it from (imagine building furniture from ready-made sections rather than starting by sawing all the planks and making all the screws yourself).

You can think of it as an intermediate layer between what's on screen and what's in storage - which, in more complicated applications, will not always be structured or displayed in the exact same way as each other, hence the need for an intermediary. Sometimes the display and the storage will not even be on the same computer (like in websites such as this one).

So I imagine the purpose of this assignment might be to get you used to using those structures, but without making the overall goal too complicated. The true purpose of the exercise is not always the obvious one.

Related