Object-oriented – Do serialization functions belong in a model or a controller

mongodbobject-orientedserialization

I'm developing an application where:

  • Models keep data as a multi-dimensional array, which are saved as-is to a MongoDB database. The model is used to provide methods to manipulate the data, and outside of those methods, the data properties are read-only.

  • The model factory instantiates each object in a standardized way and allows shorthand "queries" to look up a database entry and instantiate an object with it at once.

  • The "view" is Javascript, and all it does it ask the controller for certain things, and the controller responds over HTTP with JSON.

  • The controller uses the model factory to instantiate model objects and do whatever the view is requesting, if possible. It always returns JSON.

Generating that JSON is currently in a "helper" class, which I'm trying to eliminate. The serialization of MongoDB data involves converting MongoDates, MongoIDs, and other Mongo objects to strings. It's needed in the controller to output these to the browser as strings – for the most part, the controller knows how to output data to the view. But in some cases, it's needed in the model to tabulate multi-dimensional array data into a list before the controller gives it to the browser. The controller doesn't know enough about the model to do that tabulation.

Is a helper class unavoidable here? Or should 100% of serialization take place inside of the model? Should I leave the serialization function in the abstract model and use it from the controller with a static call?

Best Answer

I think the serialization to JSON is a web concern (infrastructure), not necessarily a model concern. So invoking a helper from the controller to do the serialization is fine, I would regard it as desirable. It handles a pretty clear concern, I think it's a valid component.

The tabulation you mention however sounds like it is a model thing, I would avoid doing implicit model tranforms during the serialization step. See if the controller can ask for this tabulated model directly or if the model can supply it transparently if you don't want the controller to know about it. Either way make sure the data is fully prepared before you give it to the serializer. If the tabulation is specific to one view I might do this tabulation in a 'view model' that I situate between the views and the (domain) model.

Related Topic