I’m making my first Java project, and trying to learn OO programming as well as MVC.
Say that you have a class “Products” and a number of objects of that class. Your GUI want to display a list of these objects, possibly also with some filter etc. I can think of several ways to do this:
- The GUI could simply read all objects and list them.
- Make a globally available method that returns all the objects. This could be placed in some kind of repository for global functions.
- Make a static method inside the Products class that returns a list of all objects.
What is the proper way to do this, and where would you put the code?
As you want to learn MVC, you already know that in order to implement MVC pattern you need three layers: Model, View, Controller. In your case, you have the two of the layers, Model (Product) and View (ProductGUI, assuming this is a different class). What you are missing is the Controller.
In order to leverage from MVC, I suggest you to implement the Controller layer with an API approach so that you have an interface,
ProductController; and a class implementing the interface,ProductControllerImpl. This interface-class separation lets you to switch between alternative implementations and also allows Mocking your services for user interface testing (See Wikipedia for further explanations).Let me also try to explain this with a simple example.
Assume you create the interface for your Controller layer as such:
Then you can create a Mock implementation for this interface for testing purposes as such:
Note: Assumining you have a NameFilter class that aims at filtering Product’s by name.
If you decide to use a database to store your products, then you can implement
ProductControllerDatabaseImplwhich will query your database and retrieve entities for listing and which will most probably introduceWHEREclause to the query forlistProducts(NameFilter)method.Actually, things are never this simple. What is shown in this example will be referred to as DAO (Data Access Object) in more complex applications and there will be a separate layer, generally called Business layer instead of Controller layer, which will implement the actual logic for the application. But I tried to keep the example as simple as possible for simplicity.