why separate navigation rule from code in MVC - ios

more and more frameworks are trying to separate navigation rules from code. for example, JSF got "navigation-rule" tag in faces-config.xml to control page flows. new xcode 4.2 introduced storyboard so developers don't have to write code to handle navigation between scenes.
my question is why it's so important to separate navigation flow from code. what's wrong with writing code in controller to handle pages flow?

Off the top of my head: having a navigation flow specified in a single place makes it easier to understand a codebase you're not familiar with – you can see exactly how you can get to a given view without having to hunt this down.
You mention the storyboard editor in XCode – another advantage would be that having the navigation structure as a first-class entity makes it toolable.
If your framework (maybe one of the umpty Java page flow frameworks?) also checks whether a user sticks to this flow, it's possible to easily catch errors that would happen if the intended flow is violated. (E.g. if the user tries to open the middle of a "wizard" type interaction.)
Using such a framework imposes a cognitive overhead compared to "straightforward" code. That doesn't mean you should ignore patterns at abstraction levels higher than "controller method code", or you'll turn straightforward code into spaghetti code. Obviously the benefit of formalising your navigation flow increases with the number of views in your app and the complexity of the connections between them.

Related

Ios Application structure

I still a beginner in iOS Development and while building my first app I had the following doubt:
which is considered a better development criteria, having too many views in the app or having less views with more complicated class codes so that these view can be dynamically used?
I really would love to get your feed back as in my first app i can either use 17 view (simple and strait forward) or reduce them to 6 (complicating the codes and using much less classes eventually).
It depends on the project requirement that how many views will have. It may be a topic of debate. You should have necessary views and classes but not more and unnecessary view is good. Also, to reduces the view you should not complex your classes.
You should follow the OOP (Object oriented Programming). That means,your need to write your methods/classes ,so that it can be reused.

How evil is a UIViewController?

This is a somewhat open ended question about the UIViewController class, and their proper role in an iOS app.
I recently read this article, and I partially agree with the author. It's obviously important that every bit of logic related to your views and models doesn't end up getting dumped into the UIViewController, but it seems a bit extreme to build all of your views separately and use delegate methods to access the actions.
I'm curious about which design is most efficient in regards to the memory and performance of the app (clearly an important consideration when dealing with mobile apps)? As the author of the post pointed out, Apple doesn't seem to strongly advocate against putting logic in the UIViewController.
Ultimately, I'd like to know the right way of doing things. So the question is, should the views and any logic associated with it be completely separated out of the VC? Should I really be using delegates to communicate with the UIViewController?
A view controller is not evil by nature, although it's common for them to grow into monolithic messes because they are so convenient to extend.
…it seems a bit extreme to build all of your views separately and use delegate methods to access the actions.
Think of it as breaking up your program into smaller units, whatever that may be. Subclassing UIViews in every case isn't the best solution (as one example).
Each developer's tolerance is a bit different and it varies by program/case, but it's pretty easy to recognize and eliminate duplicate code, and to break your programs down into smaller units.
I think most classes:
should not exceed a few ivars (e.g. 2)
should not require more than 100 lines
should favor composition over inheritance. in many cases where you think you need inheritance, protocols may be used.
Of course, there will be exceptions.
I'm curious about which design is most efficient in regards to the memory and performance of the app (clearly an important consideration when dealing with mobile apps)?
It matters more that you will gain a lot by writing more reusable programs. Invest more time and effort into these reusable designs, reduce duplicate code, and focus on quality. Write performance and memory into your designs where it is a concern. Generally, this will result in a big win when compared to the dreaded freshly written, poorly tested, monolithic VCs.
Ultimately, I'd like to know the right way of doing things. So the question is, should the views and any logic associated with it be completely separated out of the VC? Should I really be using delegates to communicate with the UIViewController?
Oversimplification: No, you don't have to go that far if you eliminate redundant code, focus on reusability where applicable, and ensure your units/classes maintain low complexity. Absolutely, fix those problems before they grow into monolithic classes, regardless of whether they are VCs or another type.
I've also read this article a year ago, when I was looking for better iOS coding practices than what you see everywhere (dumping all kinds of crap in view controllers...). I agree with its points, although unfortunately it doesn't provide any kind of solution to the problem.
After a year of working on a fairly large iOS application, with complicated data model, remote services and highly nonlinear navigation, my experiences come down to these points:
Use view controllers for a single unit of user interaction, like prompting for login credentials etc. Basic validation (e.g. checking for empty fields, number formats etc.) takes place in the view controller, but if validation is part of your business logic, it should be put in your model.
I usually have a so-called controller object which orchestrates the UI flow, and connects it with the domain model. The controller receives user input from the view controllers via delegate mechanisms, so they're loosely coupled.
A single monolithic controller should be avoided; so I usually try to split my controller functionality between simpler, modular parts. For example, I have a controller which manages a registration process with a mostly linear UI flow, and its embedded in the main controller of the application so its

What are the best practices for Asp.net MVC page construction, allowing for parallelism and efficiency?

I found it difficult to argue with anything in this critique of ASP.net MVC's framework for page composition.
http://www.matlus.com/problems-with-asp-net-mvc-framework-design/
Particularly these points:
No access to view or partial view instances
ViewData is your loosely typed information carrier
Controller is not really in control
Child Actions have no sense of the Request Context
Views are coupled to controllers
For small applications, I don't think that a lot of these prove to be much of a problem, but in large applications where you want to reuse a lot of shared components, or even if you just have a large application that depends on multiple backend sources of information to obtain all of the information necessary to render a view, it starts to break down.
Various half-solutions to these problems have been proposed but they do not appear to scale well or have undesirable design constraints.
Here is an example application scenario:
50% of page content is common across all pages within an application (header, footer, menus, etc.)
Your application may actually be comprised of multiple areas, each with their own controllers, etc. for independent development.
A number of the page elements (menus, page header information, footers, disclosures) that are in the common page content require one or more service calls to fill out the data for rendering.
Okay, so in asp.net mvc3, let's say that you decide that you want to share a common Razor layout that contains the 50% common UI markup. This assists with Separation of Concerns in that application developers don't need to be concerned about common ui and can focus on the logic and views specific to their domain of expertise.
However, this completely breaks down in the case that this shared layout needs data (some semblance of one or more model types) to render itself completely. You may have independent elements on the page that each need a particular data model, such as:
* primary menu model
* secondary menu model
* footer links model
* authorization model
* footer disclaimers model
And each of these models may have separate sources. So although you can share the template, there is not an easy way to share the logic to build each of these models -- and there is definitely not one that is generic, extensible, and performant that I have seen.
Some approaches to this problem that I have seen are:
Strongly type the common layout, which requires all view models to subclass a common base model class. (but there is no general solution to populating such a meta-model, and this is limiting in design and makes models huge and harder to test) Additionally, model population still falls to every controller, violating the Separation of Concerns and Single Responsibility Principle and complicating unit testing controllers by piling on lots of extra logic to populate the meta-model in addition to the view-specific model information.
Leave the common layout untyped, so you don't have to inherit from a common base model, but this requires you to use ViewData or ViewBag to communicate all of the disparate models that the template needs so you lose strong typing benefits and end up with a loose data contract. You still have the problem of a lack of a general solution to populating the meta-model and all that goes along with that.
Every controller has to subclass a common base controller class to support a common layout and model. Logic for building the common aspects of the meta-model goes here. But this is not always a desirable architecture or design constraint. This does at least resolve the Separation of Concerns issues.
Instead of a meta-model, use child actions via RenderAction() in your common layout to make reusable "portlet" style widgets that each know independently how to build their data model and provide it to their view. This is really good for Separation of Concerns, but has its own litany of downsides: views effectively making service calls during rendering via the child actions, child actions are completely unaware of the original request context, violates DRY principle as each child action is unaware of what has gone before it so each could make the same service calls over and over again in the same http request, and others. Imagine 20-30 elements of a page that all needed to invoke RenderAction() independently...
There are additional cases (some seen on stackoverflow as well) where there are other problems with RenderAction() as a solution. e.g. the fact that issuing multiple RenderAction() calls in a loop results in serial execution of all of those controller methods. There is no opportunity for parallelism with RenderAction(). I/O bound service calls in each child controller action cause the whole rendering process to wait on I/O. A controller only has knowledge of its immediate view and model and nothing has a complete picture of what is going to be inside the view in order to parallelize some operations.
The author of the above critique developed a different UI model on top of ASP.Net mvc called Quartz that allows a God Controller to have intimate knowledge of the views and can hand each of them a view model so has the opportunity to parallelize service calls in a central place to build those view models. I don't know if this is the best design to provide hooks for overcoming the problems but looks promising.
My question is, what is the best practice for building a complex application on top of ASP.Net MVC that cleanly solves these problems? I have thought of a couple possibilities (although none may be practical within ASP.Net MVC--that is TBD) but someone else must have ran into this already. What are the design patterns within ASP.Net MVC or what is coming down the pike that could make this a tractable problem?
Personally, I think that the advantages of using Child Actions via RenderAction outweigh the disadvantages.
You can create 'widget' sort of elements, and wrap up their logic in a controller action - this way the view calling the widget can remain quite ignorant of what the Child Action is doing and how it is doing it - leading to a nice separation of concerns.
You have detailed the disadvantages of this approach, however I think that the negative impact can be minimised with a reasonable caching strategy.
I'm not sure there's really much more I can contribute to this "question". I think you have a good understanding of the problems and solutions, advantages and disadvantages.
In the app I'm currently working on, we utilize a couple of these approaches by having both a base model object as well as a base controller. In order to minimize roundtrips, we store some data in session and re-populate in the model by overriding the OnActionExecuted in the base controller and grab the model out of the context and set properties out of session.
I'd certainly like to hear any wonderful solutions as well, but I think these are just the tradeoffs to deal with.

Organization and Structure of iPhone/iPad Projects

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.

Does Model-View-Controller Play Nicely with Artificial Intelligence and Behavior Trees?

I come from an MVC background (Flex and Rails) and love the ideas of code separation, reusability, encapsulation, etc. It makes it easy to build things quickly and reuse components in other projects. However, it has been very difficult to stick with the MVC principles when trying to build complex, state-driven, asynchronous, animated applications.
I am trying to create animated transitions between many nested views in an application, and it got me thinking about whether or not I was misleading myself... Can you apply principles from MVC to principles from Artificial Intelligence (Behavior-Trees, Hierarchical State Machines, Nested States), like Games? Do those two disciplines play nicely together?
It's very easy to keep the views/graphics ignorant of anything outside of themselves when things are static, like with an HTML CMS system or whatever. But when you start adding complex state-driven transitions, it seems like everything needs to know about everything else, and the MVC almost gets in the way. What do you think?
Update:
An example. Well right now I am working on a website in Flex. I have come to the conclusion that in order to properly animate every nested element in the application, I have to think of them as AI Agents. Each "View", then, has it's own Behavior Tree. That is, it performs an action (shows and hides itself) based on the context (what the selected data is, etc.). In order to do that, I need a ViewController type thing, I'm calling it a Presenter. So I have a View (the graphics laid out in MXML), a Presenter (defining the animations and actions the View can take based on the state and nested states of the application), and a Presentation Model to present the data to the View (through the presenter). I also have Models for value objects and Controllers for handling URLs and database calls etc... all the normal static/html-like MVC stuff.
For a while there I was trying to figure out how to structure these "agents" such that they could respond to their surrounding context (what's selected, etc.). It seemed like everything needed to be aware of everything else. And then I read about a Path/Navigation Table/List for games and immediately thought they have a centrally-stored table of all precalculated actions every agent can take. So that got me wondering how they actually structure their code.
All of the 3D video game stuff is a big secret, and a lot of it from what I see is done with a graphical UI/editor, like defining behavior trees. So I'm wondering if they use some sort of MVC to structure how their agents respond to the environment, and how they keep their code modular and encapsulated.
"Can you apply principles from MVC to
principles from Artificial
Intelligence (Behavior-Trees,
Hierarchical State Machines, Nested
States), like Games?"
Of course. 99.9% of the AI is purely in the Model. The Controller sends the inputs to it, the View is how you represent it on the screen to the user.
Now, if you want to start having the AI control something, you may end up nesting the concepts, and your game 'model' contains a Model for an entity, a Controller for the entity which is the AI sending commands to it, and a View for the entity which represents the perceptions of that entity that the Controller can work with. But that's a separate issue from whether it can 'play nicely'. MVC is about separating presentation and input from logic and state and that aspect doesn't care what the logic and state looks like.
Keep this in mind:
The things which need to react simply have to be aware of the things to which they need to react.
So if they need to know about everything, then they need to know about everything.
Otherwise, -how- do you make them aware? In 3D video games stuff, say first-person shooters, the enemies react to sound and sight (footsteps / gunshots and you / dead bodies, for instance). Note that I indicated an abstract basis, and parts of the decision tree.
It might be wrong in your specific case to separate the whole thing between several agents, and simpler to leave it to one main agent who can delegate orders to separate processes (/begin babble) : each view could be a process which could be told to switch to any (a number of) view by the main agent, depending on what data the main agent has received.
Hope that helps.. Take it all with a grain of salt :)
It sounds like you need to make more use of the Observer/Event Aggregator pattern. If multiple components need to react to arbitrary application events without introducing undue coupling, then using an event aggregator would help you out. Example: when an item is selected, an application event is published, relevant controllers tell their view to run animations, etc. Different components aren't aware of others, they just listen for common events.
Also, the code that makes the view do things (launch animation depending on model/controller state) - that's part of the View itself, so you don't have to make your architecture weird by having a controller and a viewcontroller. If it's UI specific code, then it's part of the view. I'm not familiar with Flex, but in WPF/Silverlight, stuff like that would go into the code-behind (though for the most part Visual State Manager is more than enough to deal with state animations so you can keep everything in XAML).

Resources