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.
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.
Related
I'm currently working on a rather complex ABAP application that is going to be split into several modules each performing a specific part of the job:
one for gathering some data from multiple sources;
one for displaying that data in UI (SALV grid, if that matters);
one for doing some business things based on that data.
According to my plan each module will be a global class. However, there is some logic that may need to be shared between these classes: helper subroutines, DB access logic and so on. All of this is a set of local classes at the moment.
I know could these classes global as well, but this would mean exposing them (as well as a number of internal data structures) to the public which I would not like to. Another approach would be sharing the includes with them between my global classes, but that is said to be a bad design.
So, my question is: how do real ABAPers solve problems like this?
Here is an example of how one can access a local class defined in a report.
The report with the class.
REPORT ZZZ_PJ1.
CLASS lcl_test DEFINITION FINAL.
PUBLIC SECTION.
METHODS:
test.
ENDCLASS.
CLASS lcl_test IMPLEMENTATION.
METHOD test.
WRITE 'test'.
ENDMETHOD.
ENDCLASS.
The report which uses the class.
REPORT ZZZ_PJ2.
CLASS lcl_main DEFINITION FINAL CREATE PRIVATE.
PUBLIC SECTION.
CLASS-METHODS:
main.
ENDCLASS.
CLASS lcl_main IMPLEMENTATION.
METHOD main.
DATA:
lr_object TYPE REF TO object.
CREATE OBJECT lr_object
TYPE ('\PROGRAM=ZZZ_PJ1\CLASS=LCL_TEST')
CALL METHOD lr_object->('TEST').
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
lcl_main=>main( ).
Of course this is not a clever solution as each method call would have to be a dynamic call.
CALL METHOD lr_object->('TEST').
This could be solved however by using global interfaces that would define the methods of your classes (of course if they are not static which I assume they are not). Then you have to control each of the instances through the interface. Your target would be fulfilled then, as only the interface would be exposed globally, the implementations would remain in local classes.
You may want to do some reading on Model-View-Controller design patterns. Displaying data in a UI - would be a "view". Both the gathering and updating of data would be incorporated into a "Model" . Business logic should likely be implemented as an interaction between the view and the model in a "Controller".
That said, one approach to this is would be to utilize the friendship feature offered in ABAP OO.
As an example: create the model and view classes globally but only allow them to be instantiated privately, then grant private component access to the controller. Class definitions would be follows:
CLASS zcl_example_view DEFINITION
PUBLIC
FINAL
CREATE PRIVATE
GLOBAL FRIENDS zcl_example_controller
CLASS zcl_example_model DEFINITION
PUBLIC
FINAL
CREATE PRIVATE
GLOBAL FRIENDS zcl_example_controller
CLASS zcl_example_controller DEFINITION
PUBLIC
FINAL
CREATE PUBLIC
Additionally it may be a good idea to make the controller singleton and store a reference to it in both the view and the model. By enforcing that the controller IS BOUND when the view and model are instantiated we can effectively ensure that these three classes exist as only you desire.
Stepping back to your initial problem: I sounds to me like you're already using something like a MVC pattern in your development so your only problem is that some routines shall be used publicly by both models, views and controllers.
In this case I strongly recommend to put these routines in global available classes or to implement getter methods in your already existing classes to access those functionality.
Any hacks like \PROGRAM=ZZZ_PJ1\CLASS=LCL_TEST are sometimes essential but not here imho.
If your application is as large as you make it sound, you should organize it using multiple packages. You will certainly have to deal with non-OO stuff like function modules, data dictionary objects and other things that can not be part of a class, so using classes as the basic means to organize your application won't work outside of very small and specialized applications.
Furthermore, it sounds like you have some really severe flaws embedded in your plan if you think that "DB access logic" is something that should be "shared between classes". It is hard to guess without further information, but I would strongly suggest that you enlist someone who has experience in designing and implementing applications of that scale - at least to get the basic concept right.
What is the best (read: most technically correct) way to handle GUI's for class objects?
Say, for example, that I have a class to deal with I/O. Let's call it clsIO. I also have a form to allow the user to change various options/properties of this class, let's call it frmIO. The frmIO GUI is specific to the clsIO, it will not be used anywhere else in the application.
My application will always create an instance of the clsIO, it will load its default settings and begin its operation. The user may or may not need to show the frmIO 'settings form' so that he can configure it.
To me, it appears that the best way to handle this is to store an object reference to the form inside the class, and provide a ShowConfigForm() method, rather than instantiate the form, which in turn instantiates the class.
Is this sound design?
EDIT
I plan to reuse this class/form combo across multiple projects. I have already developed it in its own project, so i can easily transfer/import to other projects that may require it.
Simple pseudo code with my current design:
class clsIO
{
public bool Active{get;set;}
public int Port{get;set;}
public ShowConfigForm()
{
frmIO settings = new frmIO(this);
settings.Show();
}
}
class frmIO
{
private clsIO _IO;
public frmIO(clsIO IO){_IO = IO;};//constructor
private btnEnable_Click()
{
_IO.Active = true;
//etc etc
}
}
Here I only need to instantiate the clsIO. Not the other way around.
The way you've done, there's a tight coupling from clsIO to the frmIO ( which is the GUI class). This is not a good practice as this tight coupling will stop you form doing Unit Testing etc.. also in case you need clsIO to be re-used for some other operation, this tight coupling to fromIO stops you from doing so.
There need to be another class that puts them together by first instantiating the clsIO and then frmIO by passing the clsIO instance into frmIO.
This way you separate the concerns of each class and give the responsibility of wiring thins up to another one, which would be cleaner.
Furthermore you can improve the design by extracting an interface from clsIO class and using the interface type within the frmIO to refer to clsIO. this will help you to have a loose coupling bewteen the 2 classes.
let me know if you me to provide a code sample, if what I described doesnt make much sense.
Usually you would have a class containing the configuration. The form itself has a reference to that settings class. If the user changes a setting in the form, the form tells it to the settings class/object.
Now you can register your clsIO as an observer on the settings. Meaning whenever something changes, the clsIO gets notified and can update its operations (this way around, the settings would contain references to all of its observers). This is known as the observer pattern. Has its strength if many 'unknown' objects observe something. I mean, settings may be something, which would impact on many different classes/objects. The observers only decide on the settings, but never change them.
If you want to keep it simple, without much effort, just add a reference to the settings in your clsIO. It's a design you can choose. This one is simpler, so if its a small and simple application, it should be sufficient.
But what I think you should really do is, separate the form from the values. A form is just a view, while the actual values are contained in another class.
I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.
My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.
So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?
My code:
class RefData
{
Matrix mX;
Vector mV;
int mA;
bool mB;
getX();
setB();
update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.
}
or,
class RefDataUpdater
{
update(RefData*); // something like this ?
}
There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.
And the answer is it depends. It depends on what you are trying to accomplish in your design--and
if you might have more than one data-object that exhibit similar behaviors.
First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.
So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.
All this being said, as Robert Martin points out in the book:
There are ways around this that are well known to experienced
object-oriented designers: VISITOR, or dual-dispatch, for example.
But these techniques carry costs of their own and generally return the
structure to that of a procedural program.
Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.
As already written, it depends, but I'd probably go with an external support class that handles the update.
For once, I'd like to know why you'd use such a method? I believe it's safe to assume that the class doesn't only call setter methods for a list of parameters it receives, but I'll consider this case as well
1) the trivial updater method
In this case I mean something like this:
public update(a, b, c)
{
setA(a);
setB(b);
setC(c);
}
In this case I'd probably not use such a method at all, I'd either define a macro for it or I'd call the setter themselves. But if it must be a method, then I'd place it inside the data class.
2) the complex updater method
The method in this case doesn't only contain calls to setters, but it also contains logic. If the logic is some sort of simple property update logic I'd try to put that logic inside the setters (that's what they are for in the first place), but if the logic involves multiple properties I'd put this logic inside an external supporting class (or a business logic class if any appropriate already there) since it's not a great idea having logic reside inside data classes.
Developing clear code that can be easily understood is very important and it's my belief that by putting logic of any kind (except for say setter logic) inside data classes won't help you achieving that.
Edit
I just though I'd add something else. Where to put such methods also depend upon your class and what purpose it fulfills. If we're talking for instance about Business/Domain Object classes, and we're not using an Anemic Domain Model these classes are allowed (and should contain) behavior/logic.
On the other hand, if this data class is say an Entity (persistence objects) which is not used in the Domain Model as well (complex Domain Model) I would strongly advice against placing logic inside them. The same goes for data classes which "feel" like pure data objects (more like structs), don't pollute them, keep the logic outside.
I guess like everywhere in software, there's no silver bullet and the right answer is: it depends (upon the classes, what this update method is doing, what's the architecture behind the application and other application specific considerations).
I want to create an IList of objects that are all different concrete types, so:
var tasks = new List<ITask>();
foreach (string taskName in taskNames)
{
var task = MockRepository.GenerateStub<ITask>();
task.Stub(t => t.Name).Return(taskName);
tasks.Add(task);
}
return tasks;
The problem is that each stub object is all the same concrete type. Normally this is fine, but I have a case where I want to test each one being a different type. Can I somehow configure Rhino Mocks to do this, in this case?
EDIT:
The "you-must-be-doing-it-wrong-crew" are out in force today. Since you all seem to think I need to justify my use-case before you can take a stab at answering my question, here's what I'm doing:
ITask is in my domain model, so it's part of my business layer.
I have logic in a higher level (presentation) layer that takes an ITask as an argument.
The presentation layer logic normally executes a default Strategy on the ITask, but there can be special cases where we need to use a different Strategy, and the Strategy to use depends entirely upon the concrete type of the ITask object.
The regular Strategy pattern doesn't work here because that requires my concrete ITask objects to know about a layer above them.
Decorators still have to know about the concrete type of the object they decorate, and have to be applied either at construction time (wrong layer for this case) or when used, but then that leaves me with the same problem - applying a decorator based on concrete type.
I decided to use the same pattern used by DataTemplates (and the DataType attribute) in WPF. That is, given an object from a lower layer, see if anyone's registered a Strategy to handle that type, and if so, use it. Otherwise, use a default Strategy.
So, I hope you can see why I need the test logic. So far I've had to write my own Stub factory that generates from a limited pool of concrete ITask types. It works, but I'd rather let Rhino Mocks do it for me.
You could add a ITask.Type property.
The code which is interested in the type behind the interface should then use this property instead of calling GetType(). In your tests, it then becomes trivial to take control of what the Type property returns for any given ITask stub.
Let's say I have a class like:
class NavigationData
{
float roll;
float pitch;
double latitude;
double longitude;
}
and if I want to create a method:
const bool validate() const;
which basically validates whether the 4 fields contain valid values.
Should validate() be part of NavigationData class, or should I create something like a NavigationDataValidator, that contains a validate(const NavigationData&) method.
I'm just giving a simple example, obviously my real class is a lot more complicated than this. I'm looking for good OO principles.
Put it another way: given a method, how do we know if it should belong to the class, or should belong to a separate class?
Typically it is a class's own responsibility to ensure that it maintains a logically consistent and valid internal state. For instance, Person may have a constructor that requires both a first and last name if operations on Person are meaningless without this data.
However, "logically consistent and valid" is different from "makes sense in the domain", so it is sometimes the responsibility of an external class to ensure that domain rules are obeyed. For example, PersonValidator may require that Person has a phone number which is in the US. But Person shouldn't necessarily need to know anything about whether or not a PhoneNumber is in the US.
A good rule of thumb is that if state or domain rules external to the class are required in addition to the data that already belongs to the class, you will want to consider having external validation. You may also want to centralize validation in an external class if the state of the class's instances can come from multiple sources (e.g., database, web form, file, etc.).
The right answer is: it depends.
The natural place to put such object logic is in the object itself. Sometimes though the validation rules could be dependent on a rules engine or some kind of larger "framework" which validates stuff. Another situation where you wouldn't want to do validation inside the object is when validation belongs in another tier, or layer or the application, such as the view layer.
Your class should be designed such a way and provide such methods that validate() is always true:
after any public constructor invoked
before and after any public method is invoked
(in C++-land) before destructor is invoked
Such validate() methods are called class invariants and are important part of Design by Contract.
I would say it depends. If the class's data is validatable in isolation I would put the method in the class, but if the validation requires a context then I would create a validator class based on some interface.
Depends...
Sometimes the validations are not part of the class itself, but business logic, and adding it to the class would prevent reutilization, and therefore, the usage of a validating class is good. Otherwise, the class should be able to validate itself.
I'd say have it validate itself as long as the valid values don't depend on what other classes use NavigationData.
Basically, as long as latitude and pitch has to always be between +/- 90 degrees, and longitude and roll always be between +/- 180 degrees, keep the validator in the class.
(By the way, what about heading?)
It depends on the context. Sometimes, your object is absolutely valid internally, but in the context its values aren't acceptable.
If you have simple Data Transfer Object then it probably shouldn't validate itself.
If you have a class of Domain Model then it should do some validation.
P.S. just my personal preference: isValid () instead of validate () when method returns boolean value.
As it has already been said, it depends.
But in your case, I would go for a different solution, create new immutable class for geo coordinates
class GeoCoordinates
{
double Latitude;
double Longitude;
}
And let this class validate that latitude and longitude are within valid limits. You will probably need this other places as well, for example.
class Airport
{
GeoCoordinates Location;
...
}