MVC variables in model or controller? - variables

I am trying to understand the MVC Pattern, and I finally understand a lot of it. There is one concept that I don't quite understand yet. I have looked through all the posts on here that try to explain MVC, but this one question isn't answered clearly yet.
Do you create variables in the model or the controller or both?
I can see someone passing variables from the controller to the model to change the data held within the variables, but would it be better to create them in the model then just call their values from the controller? Or would it be better to create variables in the model, and copy their values to the same variables in the controller?
If you know, please explain why one is better than the other, please. I am asking to understand, not just to know the right answer. Thank you.

If I give a straight forward answer for
Do you create variables in the model or the controller or both?
It doesn't really matter.
The main idea behind Model and Controller is
Controller resides only Presentation Logic.
Model resides only Business Logic.
So that, if you want to present your model with a different presentation logic, you can get your existing Model out and plug it with a new Controller without any problem because your business logic & presentation logic is decoupled(not mixed with each other).
This is the best diagram I found for MVC architecture. Hope you can upgrade your understanding with this.
So in terms of variables, in Model you should make variables only for business logic purpose. In Controller, it's only for presentation purpose. :))

Persistent data needed throughout the lifetime of the application should be held within the Model. Model method calls to set, get and manipulate the data within the Model should be done by the Controller.
Temporary data needed by the application or the view (for any reason) can be held in the controller... but no persistent data should ever be held within the controller, as it's considered to be a bad MVC design pattern implementation to do so.

Related

From the Model to the DTO to the ViewModel seems just too much

I know a DTO is not a ViewModel. The usage can be the same when its misused but the origion purpose is different.
I return domain entities from my Repository to the Service.
In my Service I have to reshape the entities due to the needs of my tabular view.
Now I have a conflict. Normally my service would return a DTO with the data BUT in this case the data is reshaped due to the needs of the presentation layer. Someone could say then the DTO is a ViewModel but I do not want to return a viewmodel from my service.
In this case the DTO is a ViewModel, ok the behavior is missing, but what if there is no further behavior.
Something is wrong here.
It can feel like too much, but don't overlook that it may be just right now that there is an exact match on what you're wanting to generate at the service and UI level. There is nothing inherently wrong about having those two pieces separate but nearly identical.
Often a ViewModel will be further extended to support computed fields, options for UI selection etc. It will always be easier to extend that distinct object down the road without having to blow up your service (and anyone who's taken a dependency on it).
On the other hand, I really like to follow YAGNI. So, if you honestly believe there is no way this object is likely to grow, recycling something isn't always terrible. (More context would definitely help to make this call).
Finally, don't spend so much time on the academics of it. You seem to have a pretty good handle on what you're trying to accomplish, and the only good code is shipped code. Write tests, separate what you can, but get the code out the door. I've seen projects fail because of over-engineering.
Cheers.
I feel your pain. I don't use the "repository" pattern however my service layer returns DTO's to my controller which then at some point populate most or at least some of the properties in my ViewModel. This seems like overkill at times and always raises the question "is this the best way to do things" The answer, from what I have been told and from what I have researched is "YES".
I would suggest you have a PresentationService in your controller and that object is what is responsible for returning your view model. Your presentation service then uses domain services, data services, or your repositories, or whatever else you need in order to aggregate the data to your view model.
It's ok for you to use a DTO as a view model if the shape coming from the database is what you want but if it's not and you have some other kind of data projection then a presentation service is a good practice.

yii and non database models

I need some help as I seem not to be able to grasp the concept.
In a framework, namely Yii, we create models that correspond to database tables. We extend them from CActiveRecord.
However, if I want to create a class that will get some data from other models but then will do all the computations based on those results and do something with them... then how do I proceed?
I want to clearly divide the responsibility so I don't want put all the calculations in source db based models. Basically the idea is that it will be taking some stuff from some models and then updating another models with the results of the calculations.
What do I do?
Keep all the calculations in some controller and use required models? (Hesitant about this because there is a rule to keep controller slim)
Create a none db model and then work from there (how?)?
Do something else (what?)?
Thanks for any help!
For you to use the Yii interpretation of Model, you will have to create class, which depends on CModel. It is an abstract class, thus you will be required to implement attributeNames() method.
To use other "Models" with this new structure, you will need to inject them in constructor, or right after your custom model has been created.
In real MVC model is a layer, which mostly contains two sets of classes with specific responsibilities: domain business logic and data access operations. Objects which are responsible for Domain Business Logic have no clue where the information is stored and where it comes from. Or even if there is such a thing as "database".
This video might explain a bit: https://vimeo.com/21173483

Model View Controller: Does the Controller or Model fetch data off the server?

For example: Let's say I'm grabbing a list of names and saving it to an NSMutableArray. Do I implement the method of actually calling the server to fetch the data in the controller (UIViewController) or the model(Friends object)?
It's a design decision that depends on what you're trying to accomplish. If your model only makes sense in the context of a single service, or if you want your model to provide access to all the data on the server, then build the connection to the server into your data model. This might make sense if you are, for example, building a client for a service like Twitter or Flickr.
On the other hand, if you're just grabbing a file from a server and that's the end of it, it may make sense to do the communication in the controller. Controllers tend to be less reusable and more customized for the particular behavior of the application. Keeping the specifics about where the data comes from out of the model makes the model more reusable. It also makes it easy to test -- you can write test code that just reads a local file and stores the data in the model.
That's a good question. I think the best way is through a controller because it decouples your model from requiring the other model to be present for it to work properly. Although I don't think you violate "proper mvc" by doing it in the model either.
I think you want to put it in the model. What you'll do is interrogate the model for the data and then the model will handle how to populate itself whether it's from an internal data store or an external one (like a server).
One approach is to use the repository pattern. To do this, you create Repository objects in your Model folder and you place all of you database-related methods in them. Your controllers call the repository classes to get the data. This allows you to separate the real model objects from the database accessing methods.
I use the MVCS pattern (Model-View-Controller-Store), which I discovered in Aaron Hillegass's book "IOS Programming: The Big Nerd Ranch Guide" (http://www.bignerdranch.com/book/ios_programming_the_big_nerd_ranch_guide_rd_edition_)
The store is specifically designed to fetch the data, whether it comes from a server, a local file, a persisted collection, a database, etc.
It allows to build very evolutive applications. For example, you can build your application based on a web service, and the day you want to persist your data, you juste have to modify the store, without having to modify a single line of code in your controller.
It's a lot like the Repository Pattern (http://msdn.microsoft.com/en-us/library/ff649690.aspx) (cf BobTurbo's answer)
I'd personally make a DAO, or data helper class. It's very hard to follow the strict MVC in objective C when things get more complicated. However, putting it in the model or the VC is not wrong as well.

Pattern for polymorphic views

Imagine I have a abstract "FriendEvent" model which has several different concrete implementations, ie. FriendPosted, FriendCommented, FriendUploadedPhoto etc. They should all be rendered in my view of FriendEvents, but should be visually distinct from each other (e.g. FriendUploadPhoto should include a thumbnail).
What is a good object oriented pattern to achieve this?
I'm interested to learn if there's an alternative to switching on the concrete class of the model in the view code. That somehow feels wrong because it uses conditional logic where I believe it should be possible to rely on polymorphism, but I have a hard time thinking up a better idea. Are there any established patterns to deal with this?
(I obviously don't want to implement the view logic in the model, since that would be mixing the responsibilities, and since I may want to have different views for each model)
To clarify: How to model the different event type in the model layer is not the problem. There are several well known OO solutions. The question concerns the view code which is responsible for presenting the models visually. I imagine I have an EventView class which deals with showing an event (model). The question is: How to implement this class without a switch block that selects a different code path depending on the concrete type of Event is is rendering.
Seems like you have some DoubleDispatch concerns going on here.
If I understand you correctly, you are trying to avoid mixing Model and View. Each Event class could have
HtmlString getHtmlView() { /* code */ }
but then all events have view knowledge and each time we add a new kind of view we add a new getXXXView() method. I agree that this sees unpleasant.
So we could increase the separation of concerns by having all events offer
HtmlViewMaker getHtmlMaker { return new MyKindOfViwer(this); }
Now at least we've got the View code out into its own class. Yes we may well need to write special case code for each/many kinds of events, but that's inevitable. Our first problem is where to put that special code - and that we've an answer for.
However we still have a problem: each new kind of View needs a new getXxxMaker method. So we start to look at more complex Factories and the use of Generics and Templates and so on.
For me, I would just use the partial-view concept. The base class is dealt with by the primary view, and that primary view requires a partial view that takes care of the needs of displaying the concrete class.

MVC Pattern: Where does formatting/processing type work belong? (Objective-C)

As my Cocoa skills gradually improve I'm trying not to abuse the MVC as I did early on when I'd find myself backed into a hole built by my previous assumptions. I don't have anyone here to bounce this off of so hoping one of you can help...
I have a custom Model class that has numerous & varied properties (NSString, NSDate, NSNumber, etc.). I have a need to serialize the properties for transmission. Occasionally as this data is being processed for serialization a questions may come up that the user will need to respond to (UIAlertView, etc.)
Without bogging down in too many more specifics where does this code belong?
Part of me says Model because it's about persistence of data - in a way.
Part of me says View because it's another interpretation of the core data (no pun intended) contained within the model. And the user will have to interact with dialogs on occasion as data is processed
Part of me says Controller because it's managing the transformation of data between model & view.
Is it a combination of all three? If so how would communication be handled between classes as the data is being processed? NSNotifications? Direct method calls?
This may be something that you'd want to use the Visitor pattern for -- http://en.wikipedia.org/wiki/Visitor_pattern -- because you might eventually want to use different sorts of serialization for different things and you can have different visitor classes rather than a lot of special cases in the model code.
Here's a discussion of the Visitor pattern in objective-c/cocoa: http://www.cocoadev.com/index.pl?VisitorPattern
Here's an (old!!!) article from Dr. Dobbs about the visitor pattern in objective-c: http://www.drdobbs.com/184410252
The reason that the problem you're working on doesn't fit well into the MVC paradigm is that the serialization that you're doing is like a view on a stream-based rendering surface and it is displayed. Sometimes, this can be done really smoothly in the model but sometimes it's more complex and you need to look at your case to figure out which one it is.
Frequently, the transmission/web service (or whatever) code you're using will have its own handler for this data, for example ObjectiveResource adds a serialization and deserialization handler that works as an extension to NSObject that enables it to do a lot of this stuff transparently, and you might look into that code (particularly the ObjectiveSupport part) if you're trying to do this more generically.
Typically almost all application specific code belongs in the controller. The controller should interact and observe (via notification) the model and update the view as appropriate.
If you are doing model processing such that it is something that might be re-used in another app with the same model, then that processing could be in the model.
Views can be laid out in Interface Builder or created in code and/or be subclassed for custom drawing, but they should not have application logic and would not interact directly with the model.
I would suggest putting the serialising code in the model. If the process fails it can report that to whatever's listening to it (the view / controller) which can then present the UIAlertView, correct the problem and re-submit for another attempt.
I'd say in the model.
The call to serialize the data will be done by the controller. If the data cannot be serialized then the model should return an error which the controller then has to handle.