Pattern for polymorphic views - oop

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.

Related

Nested Class - Good Design?

I have a problem where I have a main class which solves a numerical problem. For simplicity, assume that it solves Ax=b. Now, I want the user the ability to choose the method to solve it. There are thousands of options and each option has thousands of options within it.
My idea was to design it as follows: create a main class and then create subclasses for each method and subsubclasses for the details of each methods (which might interact via inheritance).
For instance, I envisage the user to do something like-
Model.method='CG' Model.preconditioning=off and then Model.Solve and in the Model class, there is a CG subclass which runs. Within CG there are methods CG_Precond and CG_NoPrecond which run depending on the preconditioning being on or off. (Assume that the methods are wildly different). So, in essence, the user is running Model.CG.CG_NoPrecond.
Is this good design? Should nested classes be avoided?
One important note is that other than the Model class, all of the subclasses contain only methods and no data of their own (other than what is returned).
I spent some time reading some really beautiful answers on SO and my problem ( I believe) aligns with the requirements of the accepted answer of Why/when should you use nested classes in .net? Or shouldn't you?.
First, you should create a class Solver and use the Strategy Pattern to create subclasses which represent the different methods to solve the problem.
The options and suboptions are a harder thing to do right. If i got you right, then CG_Precond and CG_NoPrecond should be subclasses of a CG (which is also a subclass of Solver) as they seem to share some inner logic.
If the options are like predefined values for the different methods where each method requires other values and type of values, then becomes more difficult. There i would like you to present some more examples of options, suboptions and so on.

Does MVC break encapsulation?

Let's say I have an class to model a city. Its characteristics are the following:
It has only two properties "name" and "population", both private, that are set in the constructor.
It has getters for these properties, but not setters.
I don't want any user of this class to set the properties, I want them to use a public .edit() method.
This method needs opens up a form to input the new name of the city and population, i.e.: a view. Then, if I have a view, I would like to implement the MVC pattern, so the idea would be that the controller receives the .edit() call, renders the view, retrieves the data back, and sends it to the view so that it changes its state.
But, if I do so, I have to change the properties of the city model from private to public. So, if any user instantiates my class, she/he can directly change the properties.
So, the philosophical question: Isn't that breaking the encapsulation?
EDIT Just to make it more explicit:
This city_instance.edit() method should be the only way to mutate the object.
Besides, I see that part of my problems comes from the misunderstanding that a model is an object (you can read that on php mvc frameworks), when it is actually a different abstraction, it's a layer that groups the business logic (domain objects + I guess more things)
Disclaimer: I don't really understand where are you proposing the .edit() method to be implemented, so it would help if you could clarify that a little bit there.
The first thing to consider here is that in the bulleted list of your question you seem to imply that a City instance acts like an immutable object: it takes its instance variables in the constructor and doesn't allow anybody in the outside to change them. However, you later state that you actually want to create a way to visually edit a City instance. This two requirements are clearly going to create some tension, since they are kind of opposites.
If you go the MVC approach, by separating the view from the model you have two main choices:
Treat your City objects as immutable and, instead of editing an instance when the values are changed in the form, throw away the original object and create a new one.
Provide a way to mutate an existing City instance.
The first approach keeps your model intact if you actually consider a City as an immutable object. For the second one there are many different ways to go:
The most standard way is to provide, in the City class, a mutator. This can have the shape of independent setters for each property or a common message (I think this is the .edit() method you mentioned) to alter many properties at once by taking an array. Note that here you don't take a form object as a parameter, since models should not be aware of the views. If you want your view to take note of internal changes in the model, you use the Observer pattern.
Use "friend" classes for controllers. Some languages allow for friend classes to access an object's internals. In this case you could create a controller that is a friend class of your model that can make the connection between the model and the view without having to add mutators to your model.
Use reflection to accomplish something similar to the friend classes.
The first of this three approaches is the only language agnostic choice. Whether that breaks encapsulation or not is kind of difficult to say, since the requirements themselves would be conflicting (It would basically mean wanting to have a model separated from the view that can be altered by the user but that doesn't allow the model itself to be changed for the outside). I would however agree that separating the model from the view promotes having an explicit mutation mechanism if you want mutable instances.
HTH
NOTE: I'm referring to MVC as it applies to Web applications. MVC can apply to many kinds of apps, and it's implemented in many kinds of ways, so it's really hard to say MVC does or does not do any specific thing unless you are talking strictly about something defined by the pattern, and not a particular implementation.
I think you have a very specific view of what "encapsulation" is, and that view does not agree with the textbook definition of encapsulation, nor does it agree with the common usage of it. There is no definition of "Encapsulation" I can find that requires that there be no setters. In fact, since Setters are in and of themselves methods that be used to "edit" the object, it's kind of a silly argument.
From the Wikipedia entry (note where it says "like getter and setter"):
In general, encapsulation is one of the four fundamentals of OOP (object-oriented programming). Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing.
http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
Now, that's not to say that MVC doesn't break encapsulation, I'm just saying that your idea of what Encapsulation is is very specific and not particularly canonical.
Certainly, there are a number of problems that using Getters and Setters can cause, such as returning lists that you can then change directly outside of the object itself. You have to be careful (if you care) to keep your data hidden. You can also replace a collection with another collection, which is probably not what you intend.
The Law of Demeter is more relevant here than anything else.
But all of this is really just a red herring anyways. MVC is only about the GUI, and the GUI should be as simple as possible. It should have almost no logic in either the view or the controller. You should be using simple view models to deserialize your form data into a simple structure, which can the be used to apply to any business architecture you like (if you don't want setters, then create your business layer with objects that don't use setters and use mutattors.).
There is little need for complex architecture in the UI layer. The UI layer is more of a boundary and gateway that translates the flat form and command nature of HTTP to whatever business object model you choose. As such, it's not going to be purely OO at the UI level, because HTTP isn't.
This is called an Impedance Mismatch, which is often associated with ORM's, because Object models do not map easily to relational models. The same is true of HTTP to Business objects. You can think of MVC as a corollary to an ORM in that respect.

iOS architecture and components

For quite a while I've been looking at objective c examples, watching the Stanford lectures, and playing around with some code to get a hang of creating an iOS app.
However there are a few things that I can't find a good answer on:
How do I properly separate my layers? I understand the MVC structure, and I saw some examples of creating Categories for models to implement business logic. Is that the proper way, by enriching models or should I create dedicated classes (e.g. to authenticate users, extract models from json, group orders)?
How smart should views be? Can I make a view that displays a Contact (by assigning the contact property) or should I create separate properties for all of the Contact fields or should the view request it's information via a delegate call?
I'm using a Storyboard in my application. On my screen I want to
have a navigation bar, and let's say a view that displays orders. On
other screens I want to reuse the order-view.
How can I re-use the order-view's ViewController and View in other ViewControllers?
If I have 4 screens with the same look-and-feel, do I have to simply copy them in the Storyboard? This seems like a pain to main, what if I want to change my background? Or add a button to all of the views? When I create a setup-wizard I don't want to define the look-and-feel for every screen separately.
Coming from a C# background I probably have to get into the objective-c mindset :)
Any help on this would be great.
1) ObjC-Categories will easily distort your understanding of the main problem you're facing. ObjC-Categories are completely unnecessary. You could always approach these extensions by subclassing, object composition, additional methods in the actual model, or some customization in the controller or view. So if you need to format data (e.g. which is present in the model) for display in a view -- that task would often land in the controller. As far as the examples you provide: You may opt for models in simple cases -- as well, any of the examples could merit dedicated class, if complex enough or if it would keep you from redundant implementation. Note that these may be accessory classes, which simply produce a model, or they may be composites of multiple concrete of abstract classes. Not everything needs to land squarely in the definition of M-or-V-or-C. You're free to use many design patterns with ObjC. Think of MVC as the patterns Cocoa typically uses -- you will need to know them, and you will need to know how to subclass and extend these types, but these patterns lose dominance as implementations move away from Cocoa's libraries (e.g. as complexity increases).
2) They can be smart. However, under MVC, you want to focus its implementation on the view/presentation aspect. A view which represents a collection of information could in fact perform some tasks which are typically reserved for the controller -- however, you would generally cede that the implementation were a dedicated MONContactView in doing so. If you go that route, you would generally do so for easy reusability or to achieve a simple interface. Displaying information about a Contact could be very complex - In simple scenarios, these tasks are often handled by the controller. Specifically, a MONAwesomeContactView is likely less complex (e.g. in SLOC) than MONAwesomeContactViewController (unless you have some very special drawing or layout to perform). It would be more common to set the controller's contact, and let the controller push the contact data to the views' fields. Again, in the case of a very specialized subclass -- a view could very well hold its own controllers in some cases.
3a) There's nothing wrong with creating multiple instances of a class.
3b) No need to copy. When duplication is smelled, I push the implementation to actual code -- the programs can apply the look and feel you desire, or add or manipulate the subviews as you desire. Of course, they will not be present in Xcode's NIB editor. There are of course alternate approaches, but this replication often makes me move the implementation to compiled code. Achieving a good balance of both is not so difficult (personally, I do most of my views programmatically, rather than using NIBs).
This is a pretty abstract question and it's not clear what oh mean by 'layers'. Yes, you should create your own classes where appropriate, but categories also give you the option of adding functionality to existing classes. If you can be more specific with the question it'll be easier to provide a better answer.
It's a judgement call. If you want to create a view class that knows how to display an instance of your Contact type, that's fine in my book. If that view knows where Contacts are stored in the app, though, that's not so good.
Remember that the things in a storyboard are objects, not classes. You don't want to try to re-use a view from one scene in another scene -- that'd mean sharing a view between scenes, which really won't work. If you want to use the same order-view in several places, that'd be a good candidate for creating a class. On the other hand, you can set up your storyboard so that several different scenes all transition to the same scene. If you want different parts of your app to modally display a scene that displays an order, for example, you can do that.

Naming Conventions Regarding View Models to Avoid Long Names

I am creating view models for each screen in my ASP.NET MVC application. I put all of the logic for creating a view model in a builder class. Usually, there is special logic for converting the data objects into view models, including aggregating, filtering, and sorting. Each builder is passed a dependency set, which is an object containing properties for each dependency (repositories, other builders, etc.).
The problem is that my names are getting really long. A dependency set will usually have a name composed this way:
view-model-name+Builder+DependencySet
View models usually have names composed of where you are currently and the children. For instance, my system has categorized provider definitions. So, in order to show the provider definitions under a category, I have a view model called:
CategoryProviderDefinitionListViewModel
It will look something like this:
public sealed class CategoryProviderDefinitionListViewModel
{
public long CategoryId { get; set; }
public string CategoryName { get; set; }
public ProviderDefinitionViewModel[] ProviderDefinitions { get; set; }
}
So, my builder is called
CategoryProviderDefinitionListViewModelBuilder
So, my dependency set is called
CategoryProviderDefinitionListViewModelBuilderDependencySet
That barely fits across the screen. My poor fingers are tired. Furthermore, some screens almost show the same data, so their view model names are almost the same. When I am looking through my folder, it becomes really hard to find the specific view model classes I am looking for.
Ideally, I could group my view model classes together, associating them with the view(s) where they are used. It would be nice to avoid collisions and to make names as short as possible, while keeping them meaningful. Has anyone found a naming convention/folder organization that works well in this scenario?
I've been using the "ViewModel" suffix consistently for quite a while and to be honest, sometimes I find it redundant. I think just grouping all these classes in a different namespace should be sufficient.
My understanding is that this convention has been adopted to avoid collision between domain model and view model classes (eg Product vs ProductViewModel). However, since your view models are named after the screens, it is very unlikely that you would have a class with the same name in your domain model. In fact, it should be really questionable why you have such a class in your domain model! :)
So, if you name your view model something like ViewProduct (to allow the user to view/edit a product), you don't need to call it ViewProductViewModel. See where I'm going?
Consequently, your Builder class could simply be called ViewProductBuilder instead of ViewProductViewModelBuilder.
Regarding your dependency set, I'm not sure what is your rationale behind this. But to me it looks unnecessary. If your builder has dependencies to other objects, you'll need to inject dependencies in the constructor of builder, instead of encapsulating them into another class (DependencySet) and then passing them around.
If you find your builder dependent on too may things and this is what you are trying to hide behind DependencySet, then it could be the indication of a design smell somewhere else. If classes and their dependencies are designed in a proper object-oriented fashion, behavior should be distributed very nicely between various classes and no class should have dependency on too many other things. So, hiding those N dependencies under 1 class (DependencySet) is merely treating the symptoms not the problem itself.
Hope this help :)
I prefer post-fixing my ViewModel names with "DTO". (Where DTO stands for Data Transfer Object, ie. an object that does nothing but contain information)
This is not only to avoid long names. But it also makes me able to use the same names like User, but it will be called UserDTO, indicating to me that I am working with an object that is part of my ViewModel, and thus avoid naming collisions.
I tend to agree with Mosh.
The ViewModel suffix becomes redundant the majority of the time and while sometimes you might have matching class names, it is quite easy to manage as they are confined to your ViewModel namespace. I also find that using the odd namespace alias hurts my brain less than suffixing my class names across the board.
Of course in your presenter/controller you may have naming collisions, but that could be a sign that you need to name your Views more appropriately, e.g. not User but ViewUser/EditUser.
For search results and lists I find it is best to break out something such as IEnumerable instead of IEnumerable. The latter often means you end up with a User view model class that becomes a dumping ground for all User properties that may or may not be needed across the project. This is one of the big things to watch out for and if you find yourself with a class like this, you've gone of the track somewhere. Keep your views and view models descriptive and specific. If you have many similar view models the issue is probably a bigger design problem; some designers have a tendency to reinvent rather than reuse existing graphical structures.

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.