Question

In the Model View Controller pattern where should data transformation occur?

I have a Model that stores very specific mathematical data. I need to convert that data for a physics simulator(that only accepts data in a certain format) and I'm wondering where the code for that should sit? In general where do you place code that transforms one Model into another type of Model?

Was it helpful?

Solution

Personally, I like to put this code in the constructor of the derived type of model. In this way, the code that does the conversion is in the class that needs to use it. I find this way of organizing the code makes it easier to understand, test and maintain.

Using your example, say you have a class as follows (you did not mention what language you were using, so I'll give the code below in C#, but it is very similar in java):

public class MathematicalData
{
     //members of class
}

Let's say you need to take the members of an instance of MathematicalData and transform them into another class named PhysicsSimulator. I would require the constructor to PhysicsSimulator to take an instance of MathematicalData as an input parameter, and then populate the members of PhysicsSimulator in this contructor:

public class PhysicsSimulator
{
    //constructor
    public PhysicsSimulator(MathematicalData input)
    {
        //put code here to use the members of input to populate members of this instance of PhysicsSimulator
    }
}

If the only way you want to create an instace of PhysicsSimulator is by using an instance of MathematicalData, then I would not create a default constructor for PhysicsSimulator. In this way, the only way to create a PhysicsSimulator would be to pass in a MathematicalData instance.

OTHER TIPS

It looks to me that you need to design an Adapter interface to achieve this. Making the constructor of the target(PhysicsSimulator) accept the source(MathData) object would tie them both such that when the source changes for whatever reason the target has to change.

An adapter will limit the changes to the adapter and will not force the target to change for every change in the source.

Hope this helps.

Here is a typical pattern I follow for an MVC web app. Input from the web lands in the Model, and then the Controller takes responsibility for transforming the web Model to the Business Tier model before calling the Business Tier action.

To keep the Controller from being bloated with transformation code, I'll offload transformations to AutoMapper whenever it's a fit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top