My colleague told me to separate my controllers in a separate project to make the unit testing as easy as possible, and he also told me to create a solution for the controllers project and test project to avoid loading the whole application when conducting unit testing. Is it a good approach to separate the controllers in a new project?
I am not sure if there is a simple yes or no answer to this question. I would think that your project would have to be very, very large as to have impact on your unit testing. My personal opinion is to leave the controllers in the web project along with the views and view models. However, I am a fan of moving the models to a separate project. My reasons for doing so have less to do with easier unit testing but rather reusing the data access (models) in other applications.
In my opinion you should always at least separate the controllers from your view project (usually a web project for me), because the idea is that the controllers should be able to be used with any view (maybe later you decide to use them for a Windows Forms project, for example). It keeps the namespaces a bit cleaner as well.
From my point of view, making you move out the controllers to a separate project has two things to consider, if you do so, then it enforces you to think how to solve problems with low coupling and precisely low coupled classes can be tested more easily than tight coupled classes.
On the other hand, having the controllers in the same project than the views is kind of logical because the controllers normally know about the views.
If you think of reusability there may be something arguable here because often controllers are "glue" components this means, there is a lot of wiring in them.
This seems like a good idea at first. Creating a prensentation layer in the middle and keeping your MVC project containing only views, making it truly a UI project. On the other hand, you will probably lose the tooling support for the views. Since you have to ignore all the warnings, you have to make sure all views are there, strongly typed to your object.
I don't understand the concern for referencing your MVC project in your test suite since you will probably bring in the MVC namespace anyway.
Related
I'm building a MVC4 app, I've used EF5 model first, and kept it pretty simple. This isn't going to a huge application, there will only ever be 4 or 5 people on it at once and all users will be authenticated before being able to access any part of the application, it's very simply a place order - dispatcher sees order - dispatcher compeletes order sort of application.
Basically my question is do I need to be worrying about repositories and ViewModels if the size and scope of my application is so small. Any view that is strongly typed to a domain entity is using all of the properties within that entity. I'm using TryOrUpdateModel in my controllers and have read some things saying this can cause a lot of problems, but not a lot of information on exactly what those problems can be. I don't want to use an incredibly complicated pattern for a very simple app.
Hopefully I've given enough detail, if anyone wants to see my code just ask, I'm really at a roadblock here though, and could really use some advice from the community. Thanks so much!
ViewModels: Yes
I only see bad points when passing an EF Entities directly to a view:
You need to do manual whitelisting or blacklisting to prevent over-posting and mass assignment
It becomes very easy to accidentally lazy load extra data from your view, resulting in select N+1 problems
In my personal opinion, a model should closely resembly the information displayed on the view and in most cases (except for basic CRUD stuff), a view contains information from more than one Entity
Repositories: No
The Entity Framework DbContext already is an implementation of the Repository and Unit of Work patterns. If you want everything to be testable, just test against a separate database. If you want to make things loosely coupled, there are ways to do that with EF without using repositories too. To be honest, I really don't understand the popularity of custom repositories.
In my experience, the requirements on a software solution tend to evolve over time well beyond the initial requirement set.
By following architectural best practices now, you will be much better able to accommodate changes to the solution over its entire lifetime.
The Respository pattern and ViewModels are both powerful, and not very difficult or time consuming to implement. I would suggest using them even for small projects.
Yes, you still want to use a repository and view models. Both of these tools allow you to place code in one place instead of all over the place and will save you time. More than likely, it will save you copy paste errors too.
Moreover, having these tools in place will allow you to make expansions to the system easier in the future, instead of having to pour through all of the code which will have poor readability.
Separating your concerns will lead to less code overall, a more efficient system, and smaller controllers / code sections. View models and a repository are not heavily intrusive to implement. It is not like you are going to implement a controller factory or dependency injection.
Suppose you have a project with many developers working on the same Asp.net MVC application. Project is a long run one, so team members will change over time. This means that during this time we get to a point where certain views seem (totally) different to others. Markup wise.
In order to keep the UI as consistent as possible over time let's say that initial team develops a sort of fluent Html helper methods, for creating generic view structure. Ie:
Html.CreateHeader("Header text")
.CreateForm(Url.Action(...))
.AddSegment("Person")
.EditorFor(model => model.Person)
.AddSegment("...")
.EditorFor(model => model.Company)
...
Although this does add an additional abstraction over everyday Asp.net MVC view code, but it makes views consistent over time. Of course when these fluent helpers are used.
But. Even though each of these helper methods can be unit tested I wonder what good it is to test views themselves?
Questions
My opinion is that you don't unit test anything static (ie. views). So unless views have rich client side functionality, nothing should be tested. But if it does, you would be testing Javascript code with ie. QUnit library. Is this thinking correct or does it really make sense to test something that is intrinsically static in nature and we'd only be testing presence of certain elements and their content?
What other aspects of views can be tested and why should they be tested?
During my development I've noticed that unit testing should only be done on non-trivial code. In other words methods that have at least one branch should be tested, and others that are long enough to not be completely obvious what they do even without branches.
I tend to avoid writing unit tests for methods that are trivial in nature, because they don't aid anything except consuming developer's time.
Views should only be presenting the data that is provided to them, therefore there shouldn't be any logic to test anyway.
In my opinion the "testing" of views comes under integration testing. (Checking everything looks ok, links go to the right places etc.)
In learning about Core Data, I've noticed how (in Xcode's templates) Apple directly used the query classes inside the view controller. This seems like it is bad MVC (having database access logic directly inside the view controller). Would it make sense to abstract out these kinds of actions to a separate suite of classes that obtain the data from the database and pass it back to the view controller calling it?
EDIT–
So, just to be clear, when I say "kinds of actions", I specifically mean CRUD Operations. Though if you have ideas about other things that a so-called "Model-Controller" would do, I'd be interested in hearing about them.
It's a matter of opinion, and often yes the templates are the most simple form of working example. It's hard to have a template spin out multiple files, for example.
Yes, personally, I generally spin out a separate NSManagedObject subclass. I like to have a _MySubclass object that has all the auto-generated stuff, then have the model actually reference MySubclass which has model-based business logic (you can use mogenerator or other methods to do this too if so inclined). Perhaps thinking of it as "Model-Controllers" and "View-Controllers" is another way of putting it.
This is a very good question and the answer likely depends on your situation. Perhaps architecture purists would insist on separate Model controllers and there are a lot of benefits to this approach. However, sometimes I find myself using Key Values when I'm doing a simple view. When things are more complex, for example, when coding the same Model for the Mac and iOS, having separate Model Controllers will allow you to reuse a lot of code. When you must diverge, Obj C Categories are a very clean way to extend functionality without adding a lot of overhead. I personally favor categories over extensive subclassing.
Since NSFetchedResultsController was released, my model classes are leaner. There are a lot of nuances to this and experience will help you come up with the best solution for your App. I've also found that writing unit tests up front will help you force through issues and validate your design, or send you back to the drawing board :)
I've never worked with MVC design pattern before and recently I started to work on the project using ASP.NET MVC.
I'm using ActiveRecord as my data layer.
I'm also using view models (unique for each view) and AutoMapper to map my view models to EntityFramework entities.
In a few days reseaching about MVC, EntityFramework and reading different articles I came up with the following design:
In my solution I have Web project (Presentation Layer) which contains Views and Controllers.
I have Core project where I define my ViewModels and Services (Business layer where all business logic goes)
I have EntityModels project where all me EF entities live (Data layer)
This design allows me to keep my Data layer separate from my Presentation layer, Web project doesn't know anything about EntityModels project and vise versa, all the logic lives in business layer.
From my controllers (after validation checks) I pass viewModels to Service layer where mapping and all necessary busines logic is executed.
Is this design correct at all?
My consern is that I've read that ViewModels should be defined in Presentation Layer. I saw examples where Presentation Layer has references to Data layer and mapping is done in controllers (good practice?). in this case controllers pass domain models to business layer. I don't have any experience here but I don't like it.
So, can anyone point out where I'm right and where wrong?
thanks in advance.
Overall the architecture looks good. The decision on where to place you view models hinges on one factor in my opinion.
Do you plan to have other clients in the future that may benefit from reusing those view models (iPad, Android, etc.)?
If so, definitely keep them out of the MVC assembly and put them in their own assembly. Otherwise, you're safe putting them in the MVC app as long as you're ok with moving them and changing code if you ever decide to make a second client.
For the record, I always put my view models in their own assembly. It doesn't take more time up front, but it pays dividends down the road if things change.
FWIW, I am doing the same thing - but I am new to MVC, so not 100% sure I'm on the right path also. But, it just "feels right", which more often than not tells me it is correct.
The only thing I would add is that I use automapper (automapper.org), which almost eliminates the overhead of having the layers. Definitely check it out IMO.
I have to say the only thing that doesnt feel 100% correct is that with this pattern, we are creating a whole lot of ViewModels -> one per View. I assume you mean that Create, Index, Update, Details for each domain entity EACH have their own ViewModel? Or are you sharing one ViewModel between the views?
Lastly, I dont buy jfars argument that it creates lots of complexity/build time. At the very least, it conceptually separates the layers that much more. It strikes me as a much better job of separating the concerns, with very little overhead.
I have a pipe dream of reusing the viewmodels for a silverlight implementation, but havent really thought that one through yet. But it makes sense that if you do a good job of factoring out all "non-UI" code into the viewmodels and services, then doing a new UI should be "trivial", right? we'll see :-)
I've been developing iPhone apps for a while now and something that's always peeved me is that I haven't found a comprehensive way to organize my application files.
I know that an iPhone project is technically MVC, but it seems like most everything I do is in a ViewController. I notice that as a project goes on, my ViewControllers continue to get more and more bloated and I can't help but think that there has to be a better way than this. I also do some ruby on rails and I like the fact that on that platform there is such a clear separation of concerns and an established way to organize an application.
Has anyone discovered a way that they especially fond of for organizing the application?
Also how do cut back on the view controller bloat?
I agree, just about everything seems to land in view controller classes, and they get unwieldy in a hurry. There are several things you could try:
Create separate classes for delegates, if they don't actually need to be part of the view controller;
Put delegate method implementations into a category, as described here;
Factor out any methods that don't actually interact with the rest of the view controller, and put them in separate classes
Use blocks for asynchronous callbacks when they make sense, because they are often less verbose than explicit callback methods;
Or even just organize your methods carefully and use #pragma mark so Xcode can help you navigate through the file.
This isn't an exhaustive list, of course, and others may have better suggestions.