MVC Views: Display Logic? - model-view-controller

I've been reading this paper: Enforcing Strict Model-View Separation in Template Engines (PDF).
It contends that you only need four constructs within the views:
attribute reference
conditional template inclusion based upon presence/absence of an attribute
recursive template references
template application to a multi-valued attribute similar to lambda functions
and LISP’s map operator
No other logic is allowed within the view - for example if (attr < 5) would not be allowed, only if (valueLessThanFive)
Is this reasonable? Most MVC frameworks allow any logic within the views, which can lead to business logic creeping into the view. But is it really possible to get by with only those four constructs?
For "zebra striped" tables, the paper suggests mapping a list of templates onto the list of data - for example:
map(myList, [oddRowTemplate, evenRowTemplate])
But what if you want to make the first and last rows different styles? What if the 3rd row should be purple on Tuesdays because your graphic designer is mad? These are view-specific (for example if I was outputting the same data as XML I wouldn't use them) so don't seem to belong in the model or controller.
In summary:
Do you need logic above the four constructs listed above within views?
If so, how do you restrict business logic creeping in?
If not, how would you make the 3rd row purple on Tuesdays?

Terence Parr is a very smart guy and his paper has much to commend it, but from a practical point of view I have found using just these constructs somewhat limiting.
It is difficult to prevent business logic creeping in especially if you have the ability to do anything, as for example ASP.NET and JSP would give you. It boils down to how you spend your time:
Allow limited additional functionality (I'm not an advocate for "anything goes") and use code review mechanisms to ensure correct usage, or
Restrict to the four constructs above, and spend more time providing attributes like valueLessThanFive (remembering to rename it to valueLessThanSix when the business requirement changes, or adding valueMoreThanThree - it's a bit facetious as an example but I think you'll know what I'm getting at).
In practice, I find that allowing conditionals and looping constructs is beneficial, as is allowing property traversal such as attr[index].value in template expressions. That allows presentational logic to be effectively managed, while incurring only a small risk of misuse.
Allowing more functionality such as arbitrary method calls gets progressively more "dangerous" (in terms of facilitating misuse). It comes down, to some extent, to the development culture in place in your environment, the development processes, and the level of skill and experience in your team.
Another factor is whether, in your environment, you have the luxury of enforcing strict separation of work between presentation and logic, in terms of having dedicated non-programmer designers who would be fazed by advanced constructs in the template. In that event, you would likely be better off with the more restricted template functionality.

To answer your question about the 3rd row purple on Tuesdays:
The original (or one of the very early) MVC patterns had the 'View' being a data-view, there was no concept of a UI in the pattern. Modern versions of the MVC pattern have felt the need for this data-view which is why we have things like MVVM, MVP, even MV-poo. Once you can create a 'view' of your data that's specific to the UI View it's easier to solve lots of the concerns.
In our case our 'model' is going to get extra properties on it, such as Style or Colour (style is better as it still lets the view define how that style is represented). The controller will take raw 'model' items and present to the view custom 'model' items with this extra Style, giving the 3rd row on Tuesdays a style of 'MadDesignerSpecial', which the view uses to apply the purple colour.

Related

Is there such a thing as ‘class bloat’ - i.e. too many classes causing inefficiencies?

E.g. let’s consider I have the following classes:
Item
ItemProperty which would include objects such as Colour and Size. There's a relation-property of the Item class which lists all of the ItemProperty objects applicable to this Item (i.e. for one item you might need to specify the Colour and for another you might want to specify the Size).
ItemPropertyOption would include objects such as Red, Green (for Colour) and Big, Small (for Size).
Then an Item Object would relate to an ItemProperty, whereas an ItemChoice Object would relate to an ItemPropertyOption (and the ItemProperty which the ItemPropertyOption refers to could be inferred).
The reason for this is so I could then make use of queries much more effectively. i.e. give me all item-choices which are Red. It would also allow me to use the Parse Dashboard to quickly add elements to the site as I could easily specify more ItemPropertys and ItemPropertyOptions, rather than having to add them in the codebase.
This is just a small example and there's many more instances where I'd like to use classes so that 'options' for various drop-downs in forms are in the database and can easily be added and edited by me, rather than hard-coded.
1) I’ll probably be doing this in a similar way for 5+ more similar kinds of class-structures
2) there could be hundreds of nested properties that I want to access via ‘inverse querying’
So, I can think of 2 potential causes of inefficiency and wanted to know if they’re founded:
Is having lots of classes inefficient?
Is back-querying against nested classes inefficient?
The other option I can think of — if ‘class-bloat’ really is a problem — is to make fields on parent classes that, instead of being nested across other classes (that represent further properties, as above), just representing them as a nested JSON property directly.
The job of designing is to render in object descriptions truths about the world that are relevent to the system's requirements. In the world of the OP's "items", it's a fact that items have color, and it's a relevant fact because users care about an item's color. You'd only call a system inefficient if it consumes computing resources that it doesn't need to consume.
So, for something like a configurator, the fact that we have items, and that those items have properties, and those properties have an enumerable set of possible values sounds like a perfectly rational design.
Is it inefficient or "bloated"? The only place I'd raise doubt is in the explicit assertion that items have properties. Of course they do, but that's natively true of javascript objects and parse entities.
In other words, you might be able to get along with just item and several flavors of propertyOptions: e.g. Item has an attribute called "colorProperty" that is a pointer to an instance of "ColorProperty" (whose instances have a name property like 'red', 'green', etc. and maybe describe other pertinent facts, like a more precise description in RGB form).
There's nothing wrong with lots of classes if they represent relevant truth. Do that first. You might discover empirically that your design is too resource consumptive (I doubt you will in this case), at which point we'd start looking for cheats to be somehow skinnier. But do it the right way first, cheat later only if you must.
Is having lots of classes inefficient?
It's certainly inefficient for poor humans who have to remember what all those classes do and how they're related to each other. It takes time to write all those classes in the first place, and every line that you write is a line that has to be maintained.
Beyond that, there's certainly some cost for each class in any OOP language, and creating more classes than you really need will mean that you're paying more than you need to for the work that you're doing, which is pretty much the definition of inefficient.
I’ll probably be doing this in a similar way for 5+ more similar kinds of class-structures
Maybe you could spend some time thinking about the similarity between these cases and come up with a single set of more flexible classes that you can use in all those cases. Writing general code is harder than writing very specific code, but if you do a good job you'll recoup the extra effort many times over through reuse.

Cocoa method naming convention: With vs For

I am looking for a general consensus or opinions on With vs For as in things like:
-(NSImage *)imageWithStyle:(MyImageStyle)style
-(NSImage *)imageForStyle:(MyImageStyle)style
-(id)controllerWithView:(NSView *)view
-(id)controllerForView:(NSView *)view
Thoughts?
When you use one over the other and why?
I tend to work on the basis that if A has no relation to B, but aspects of B might change what A will do, then you're making an A with information from B.
If A has some relation to B, e.g. B has a way of listing all the A's that are associated with it, then I'll be making an A for (on behalf of) B.
The controller is a good example. If it's a controller being made with a view, it implies that the controller isn't "for" anything, it's just some controller, but it's using bits or all of a view to do Things. But if it's a controller for a view, then now we've implied a permanent association - this is a controller that is for, i.e. that controls, the view. So here, I'd use controllerForView.
In the image and style example, I imagine your intent is that some object describes default aspects of the images being built. I'd use imageWithStyle. Everyone likes an image with style... ;-)
It's subtle either way though. You could consider less conventional but clearer terms if you think there is ambiguity - e.g imageFromTemplate or imageBasedOnStyle. Cocoa tends to be more about almost-English legibility and less about being terse.

Why create nodes in their own method?

I see a lot of javafx code something like this:
private Button getButton(){
Button myButton = new Button("A button");
myButton.setOnAction...
}
private HBox toolbar(){
Button file = new Button("File");
Button edit = new Button("Edit");
Button props = new Button("Properties");
HBox toolbarArea = new Hbox();
toolbarArea.getChildren().add(file, edit, props);
}
I'm interested in an explanation of why this is done (which I haven't found).
The small method approach works well for internet demo code
Rather than using small methods to define UI elements, the alternatives are:
A very long method unless the application is completely trivial.
FXML defined UI (usually preferred for non-trivial examples, but verbose and unnecessary for small demonstrations).
Separate enclosing objects and classes (sometimes overkill if only aggregation of existing controls is required).
Small methods decrease dependencies on pre-declared objects and program state. Usually the small methods are self-contained and any inputs to them are in their parameter list - it's easier to read and understand them without needing to understand a lot of contextual information and it is also easier to unit test the methods or apply the methods to a more functional programming style, reuse the methods in lambda calls, etc. The names of the small methods also make them self-documenting, so the code is more readable without adding additional comments.
So, in a lot of small, example JavaFX applications you see on the internet, you will find the approach of small methods to describe UI elements, though such an approach is not always the one you should use when you are building larger applications.
Using small methods for UI component definition is an example of an extract-till-you-drop method of programming. Of course, as you can see in the comments on the linked extraction blog, everything is debatable and opinionated, so use your best judgement, but when in doubt, I'd argue in favor or method extraction, not just in the UI definition code, but in your functional code as well.
A concrete example
Take a look at the discussion of JavaFX programming style in the comments on this blog. This is based on this original clock app sample, which does not use small methods, and an updated clock app sample, which is built around many small methods. Per's Lundholm's comment on the original code was this:
A typical sign of not doing it right is when you write comments. Don’t write comments in your code, write code that reads well without comments!
I read you code and I think it is virtually unreadable, with all respect. It is a long method sprinkled with constants that carries little or no meaning. If I am given such a code to change, be it fix a small bug only, I start to extract method ’til I drop. It is the fastest way of understanding code.
I suggest you review both sample code bases and decide which you would prefer to maintain. My guess is that you will decide the version with many small methods would be easier to read and maintain.
Use declarative FXML and CSS for larger applications
Also keep in mind, that for many larger applications, use of FXML and CSS is preferred over java code to define and style the UI elements - this is because a large part of defining a UI is often easier to maintain using a declarative syntax rather than a procedural or functional syntax, and FXML is declarative by it's nature (plus it is fully tooled via SceneBuilder and IDE FXML support). Study the SceneBuilder code base for an example of how to use FXML and CSS to define larger UIs.

translating using a global function in OO environment (Zend Framework)

I am working on a project build on the Zend Framework. I'm using Zend_Translate to do my translations, but I want to keep the amount of extra code in the front of my application (views) as minimal as possible. Translation of a text should look like this:
echo __("Text to translate");
Using a view helper isn't doing it, because then I get:
echo $this->__("Text to translate");
This would mean I have to declare a global function somewhere, that calls for Zend_Translate to do the rest of the magic. Because I want the project to stay as clean as possible I'd like some suggestions on where to put this function.
I have considered including a file with my global function inside of the _initLocale() in the bootstrap.
Basically my question is: am I now violating all the holy MVC principles, or is this the right way to go?
This is actually not an easy question to answer. Of course you're violating some principles of OOP because you're basically punctuating your objects with hundreds of little wholes where there should be just one. You should be injecting the translation object into your controllers and views once and then call $this->__(). This is also easily done by creating an intermediate layer between Zend_Controller_Action and your own controllers. BUT... translation is a very specific case and I don't see much potential harm coming from your solution. The Translation method is not likely to change its logics and if you need to rename it, finding and replacing two underscores followed by a bracket will most probably not yield anything else than translated strings... then again that use of 'most probably' is a smell already.
Summary: It seems more or less ok but I still wouldn't do it, especially if it's a software of some meaning with an expected life span of some years.

How to name GUI elements?

One thing that constantly causing me headache in programming is when I don't have any naming-convention in a domain where I have to deal with a lot elements. It is clearly what is happening to me when using UI designers such as Windows Forms designer.
Everytime I start a new project I am trying to reinvent a "seem-strong" naming convention but it always fail at some points. For me there is 2 main problems compared to classic code definition for naming GUI elements:
You have to place a lot of variables (GUI elements) which can all be accessed in the same scope, so you need to have to a strong naming convention to find quickly the right element.
You often need to access to a specific type of GUI control (ex: TextBox, Label, ...), so the best solution for GUI elements is to name them after their types (Hungarian style notation), which can be sometimes confusing and not helping in finding the right element quickly.
If someone has a documentation describing a good convention or a strong convention he invented for its own project, I would really like to know it!
NB: I did not classified this question under .NET or Windows Forms tags has it seems applicable to a lot of frameworks. If not, let me know.
EDIT:
In fact the convention I most use is using a reversed hungarian notation (meaning the type comes first) followed by a path based on the UI elements hierarchy. For example, to easily access to a TextBox which belongs to the "Settings" tab of my program I would call it this way:
this.tb_settingTab_xxx
My problem using this convention is that it is not perfect and sometimes fails when you have a UI element that belongs to another which also belongs to another which also belongs to ...
I am really searching for is the unbreakable and handy naming-convention. I am quitely surprised that Microsoft never gaved any guidelines concerning this. Or am I going wrong? (ie. Mark Rushakoff comment).
There are various naming conventions described in this post. The key is to remain consistent throughout the project. I deal with a lot of controls, but find it straightforward to label them based on what they are. Textbox = tbMyControl, Label = lblMyControl. The 'MyControl' bit might be the same if they relate to similar aspects (e.g. tbUsername, lblUsername). However, there's no confusion on what I'm accessing. If you find you're getting confused, then maybe you're trying too many different notations? Keep it simple and logical.
Note: I use the following in code that covers - and sometimes mixes - "raw" Win32, ATL/WTL and MFC, so don't take it literally, only the principle. (Also, be forgiving on the m_)
I use a two-letter-shortcut for standard control types, followed by the name which resembles the functionality of the control (in most cases, Identical / close to the label). The name of related controls needs to match of course - e.g.
CStatic m_stBasePath;
CEdit m_edBasePath;
CButton m_cbBrowseBasePath;
It's not perfect for all scenarios, but generally I'd say a dialog where this isn't good enough anymore might have to many controls for the user already.
I've written three paragraphs that could be titled "details and defense" - and subsequently deleted them, since there's a very clear essence:
Consistency.
I mostly use the dialog resource itself for orientation, and have strict equivalence between resource ID's and associated members. So the "Base path" - related controls aren#t together in an alphabetic order, but I rarely see this as a problem.
The standard control type already contains very obvious information about functionaltiy of a control - a checkbox to enable / disable a group of features or for a boolean option, an edit or drop down to enter/select a value, a button to open a sub dialog, a static control for the label, etc.
I'm not sure how this style transfers if you transfer it to a platform with much more controls or when you use a lot of custom controls, as my WinForms projects have been comparedly small.

Resources