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?
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.