DTO, DAO and MVC Concept

DAO Layer

Que 1 : Why do we use DTO and DAO, and when should we use them ? If you are developing a GUI Java software to do with inserting, editing, deleting data. But you are struggling to distinguish between DTO/DAO and Model, View, Controller (MVC) Structure? Are they similar, which is better to use when interacting with database through Java GUI .

Answer :DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

Que 2 : Whether it is a good practice to have view and Controller in one class. If we think about Netbeans, you can create GUI Frame Class and add components like JButton onto the frame, double clicking the button will take you to the actionListener method(Controller) which appears to be in the frame the data is to be displayed to the user (View). So they're in the same class. Is that completely going against the concept then or not?

Answer : If you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

Programming isn’t about what you know; it’s about what you can figure out.