MVC Design Patterns – Best Place to Put SQL Functionality

design-patternsjavamvcobject-orientedprogramming practices

I am wondering about best practices here.

MVC (Model – View – Controller) patterns involve separating components of your program that model the data, manipulate those models, and display those results to the user (usually through the UI) in some way.

What about a function that takes the model data and inserts it into a database? For example I have an object called a GameBoard, and I also want the ability to insert the state of this board into the SQL database for storage / historical purposes. I have a class that holds all my query functions.

But where would I call these functions from? Would this sort of functionality make the most sense to make it as a method of GameBoard? Or should it be part of the controller classes?

For example, I've got a GameBoard class and an SQLDatasource/SQLHelper class (which I call the "models"). The SQL classes have methods that take care of the queries and such. In Android, there are also Activity classes where all the "events" take place (I call these the "controllers"). The "view" takes place via code that binds the Activity to some XML. That being said, I normally instantiate the GameBoards in the Activity classes, and right now I also call the query functions from these same classes that accept a GameBoard as an argument.

Best Answer

A typical (but simplified) MVC architecture looks like this:

Database <-->  Logic Layer <--> Controller <--> View

Your Logic Layer contains the functions that you would call to perform your game-related activities. The purpose of the Logic Layer is to translate your game-related functions into database operations.