DTO, DAO and MVC Concept
Que 1 : Why do we use
DTO
andDAO
, and when should we use them ? If you are developing aGUI
Java software to do with inserting, editing, deleting data. But you are struggling to distinguish betweenDTO/DAO
andModel
,View
,Controller
(MVC) Structure? Are they similar, which is better to use when interacting with database through JavaGUI
.
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:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
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
andController
in one class. If we think aboutNetbeans
, you can createGUI
Frame Class and add components likeJButton
onto the frame, double clicking the button will take you to theactionListener
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.