Community Blogs

Blogs of different SQL/Developers Community Members
Signed in as anonymous | Edit Profile | Sign out | Help
in Search

Weblog :: Boris Ševo

Sporadic posts about my interests, e.g. software development (mostly .NET), technology in general and some occasional rant.

Using templates in applications which follows MVC pattern

Disclaimer: only purpose of this post is to continue hot Twitter conversation about using expressions which computes something in MVC views. I don't want to say that templates are the bad thing, nor that Tomislav Capan's presentation about Spark View Engine was bad ;).

Intro: Today at Croatian WebUG, Tomislav Capan had presentation about Spark View Engine for ASP.NET. Overall speaking, presentation was ok and I learned something new, but there is one thing which bothers me in the whole idea of using templates which allows all kind of operations in applications which follows MVC pattern. Here is one example of the View written using the Spark template's syntax:

<s:for each="var p in Products">
     <p class="${p.Price > 100 ? "highPrice" : "lowPrice"}">${p.Description}</p>
</s:for>

What's the problem with the above code?

Generally speaking nothing (maybe it has some syntax error, but that doesn't matter in the current context). If you need to write something fast and all you want is working code now, then the code is ok. But, if you are determine to follow MVC way of writing applications with clear separation of concerns and you want to make your code easily maintainable and testable (I'm talking about unit tests) then, you are doing it wrong.

Imagine that, after you have wrote above code, your currency significantly lose on its value. Now, the new business rule is that high price is 500. You need to change your View and change the expression p.Price > 100 to p.Price > 500. Obviously you wrote your View in a wrong way. When the business rule has changed you need to change your View instead of Controller.

The better way to accomplish the same thing is to write something like:

<s:for each="var p in Products">
     <p class="${p.PriceImportance}">${p.Description}</p>
</s:for>

where PriceImportance is some property or method in Products class which returns strings highPrice or lowPrice based on evaluation of the Price > 100 expression. Expression is written somewhere in some Controller.

You can now say that I put presentation logic outside of the View. But I didn't. Only View knows what to do with the highPrice and lowPrice values and how those values are represented. Controller even doesn't know what the highPrice and lowPrice are. It doesn't know how their representation.

View is responsible to represent highPrice. It can represent it with the red color or with the yellow color. If the business rule changes and we have highPrice, mediumPrice and lowPrice where they are represented with yellow, blue and green colors respectively you need to change your highPrice CSS class from background-color: Red; to background-color: Yellow; and everything will work. The important thing is, that this change is done in the View. The business part of the change, the fact that we don't only have high and low price is done in a Controller where expression is changed to Price > 200 ? highPrice : (Price > 150 ? mediumPrice : lowPrice).

If some other View need to use the same Controller, it can freely represent highPrice as <b>highPrice!</b>!

At the end, here are my answers on some questions which occured during Twitter conversations about the same topic:

  1. Does Controller depends on View? - in the second solution it doesn't. If you change your view from HTML View where highPrice is name of some CSS class to Silverlight View where hightPrice is key of some XAML style, everything will still work
  2. Can you unit test your business logic? - yes you can in the second solution. In the first solution? I don't think so.
  3. Does Controller knows anything about the presentation? - no it doesn't. View will represent highPrice if it thinks that it need to be represented and it will represent it as HTML, XAML, ...
  4. Why can't Controller just return value (100) and let View represent the value with the help of JavaScript? - because then you just shifted business logic from backend language to JavaScript and you have your business logic in two places -> two places for doing unit testing
Published svi 20 2010, 11:25 by boris.sevo
Filed under: ,

Comments

 

anonymous said:

Very nice post Boris.... very nice. You have opened my eyes about some questions regarding better unit testing in conjuction with mvc app developing.

I must admit, I have doing code as you in the first example, except that value 100 was "spit out" from controller, ofcourse.

In fact, when I think again, the asp.net mvc model validation works that way. If validation fails for some reason, the html validation message controls are rendered with css class atribute "field-validation-error". You can, if you wish, tweak class in css file as you wish (green font color :D).

And, for the end, some presentation logic must be present in the view: alternating rows, show/hide admin/registrated user controls etc.... Do you agree?

svibanj 27, 2010 2:32
 

boris.sevo said:

Regarding showing or hiding controls I must disagree.

I always prefare to bind views to controllers which have property like IsVisible. Then in controller, implementation of this property will be something like 'return IsLoggedUserInAdminRole();'. My experience tells me that it is very hard to define good and consistent roles. So something wich is today visible to users in admin role, tomorrow will also be visible to users which are in developer role. Becuase of this I prefer to determine what is visible in controller rather then in view (method IsLoggedUserInAdminRole will today be 'return IContext.User.IsAdmin' and tomorrow 'return IContext.User.IsAdmin || IContext.User.IsDeveloper'). Only then I can test my "what is visible logic" when requirements changes.

Regarding alternating rows and all other presentation logic which will provide zero value if it's part of the controller rather then view, I must agree.

There will be no point to have controller with property IsEven or IsOdd. Obviously it is a good thing to have template engine wich allows you (using ternary operator or something else) to determine is current item in iteration even or odd.

svibanj 27, 2010 9:47
 

anonymous said:

And in trying to emulate NYC/Van, it’s also building up for people who need to be close to the newest ‘gourmet

hamburger’ joints, pay exorbitant condo fees that will rise at the same pace as the infinite supply of units,

and want to pay 2 land transfer taxes for the privilege of never owning any land, just

some shoe-boxy space hovering over someone else’s land.

“Diet is against my religion,” Georges said. These outsource data companies implement sophisticated security systems and policies to

protect the data that they maintain on behalf of their clients.

Our precious days off gave us the opportunity to catch up with friends or with blog

posts, explore the neighborhood, or simply sleep. These functions combine

to deliver a more realistic and accurate preferred route to save you

time.

travanj 9, 2013 7:38
 

anonymous said:

The school district is also investigating the tutor, as is Child Protective Services,

because the 14-year-old’s parents filed a complaint about the incident with the Division of Child and Family Services.

Nothing builds relationships and increases productivity better than a compliment, and the beauty of this is that

everyone can afford to participate! To be fair to Crag, his

definition of the universe is traditional, but it also might

be outdated. The units are relatively expensive. What if you couldn’t remember

that one moment?

travanj 9, 2013 8:11
 

anonymous said:

L’équipe de terrain disposait enfin de sa liste de bénévoles, Build the Hope .

Tenho dúvida de qual time essa mulher torcia, mas deve ser pelo Minas pois ela esta

insatisfeita pelo fato da cubana n passar

pelo bloqueio. no, green face paint is not available to non-members for purchase.

Here he shares his personal observations on performance, recordings and composers in the region and around the world, with occasional

digressions. Last year the Coalition Government unveiled

plans to set a minimum price for alcohol in England and Wales.

travanj 9, 2013 9:04
 

anonymous said:

La mayoría de los investigadores están de acuerdo en que un nivel seguro es de máximo 0.

3 miligauss. And while it’s too early to call the Galaxy Note a success,

especially the version found on AT&T, it seems that the device has been able to carve out a niche for itself.

Also, really two separate films packed into one. The Paul campaign has rigorously organized its volunteers

to attend the mass precinct meetings that took place all over Georgia.

Une des caractéristiques de notre fonctionnement interne et externe est qu’il s’est bâti sur une culture du non

dit qui ouvre sur toute une série de dérives.

travanj 9, 2013 9:22
 

anonymous said:

@ Just Some Fuckhead : Never thought if that way. A PhD is

no guarantee of scientific integrity or expertise.

But they also say that it could have been a lot worse had the twister struck

during the peak summer tourist season. We heard about a back porch for months and fast ferries for years!

Super cute...tiny..born Dec 20 2012...will be ready

on Feb 14 in time for Valentine's Day.

travanj 9, 2013 9:54
 

anonymous said:

They later defended their integrity. They’re as bogus as muslims….

some dummy like huybbard, got high on mushrooms or toads, hallucinated about some

moroni, and got a whole bunch of other dummies to step into the moroni.

Qmonf [url=http://www.moncler-fjpt.com/]モンクレール ダウン[/url] kmtn atft qvem gcth jydv wbou Mzlrd bryw cpms

wbuv mdgw actp lyti Zhuzd xisx yffe [url=http://www.moncler-fjpt.com/]モンクレール[/url] ukoa ifaj rbux vyfk.

Bvche xmzi vmiq dlrj iukd flag tjja Kxads ssom qlgc wrgi ylmk

vrdq qyiv Llkto nrwk roog uphw ithh lvba egrm. My mind enjoys the challenge of making

stuff up, of improvisation, of unexpected relationships.

And coco's head in approximately grass-roots.

travanj 9, 2013 10:01
 

anonymous said:

Uh, Keith, I think you might have watched too many post-award speeches at the Oscars lately.

Sources say he has been endorsed by Chief Tony Anenih and Edwin Clark from the South-South, just as

Senator Abdul Ningi and Prof Jerry Gana formed other chieftains that

endorsed Bamanga from the North- East and North-Central respectively.

What is the difference between that and suggesting that blacks

(for example) are all, more or less, unmotivated? Poche cose: quelli che scaricano sempre la colpa su qualcun altro, per esempio.

In 2011, the City took in $33.75 Million from

the property tax.

travanj 9, 2013 10:04
 

anonymous said:

The parent company of stricken cruise firm Costa faces a massive

class action lawsuit after European victims of the Concordia tragedy join legal actions

in the United States. Come back Adolf, all is forgiven!

What’s also remarkable about this study is the lead author, Nathan Myhrvold.

According to details published in many papers, several dozens of Kohistani laborers were busy working

on the Karakuram Highway expansion project

in different parts of Nagar Valley, a hundred percent Shia dominated region, when the news

of Kohistan carnage came out. Realty Among the population agencies of real estate use huge prevalence today,

...

travanj 9, 2013 10:11
 

anonymous said:

Mosheen has drawn the widest gate in 20 and hoop Danny Nikolic will need to use all

his experience to get the super filly in a good spot in the run without expending too much energy.

Of course there have been concerns about what the city allows in terms

of commercial operation and home occupancy. In the back of my

mind a little voice said “those are yours” but I couldn’t imagine what they were.

Freida Giannini, unique because of this artist identify, provides seem

to be tabs on a good wholly excellent variety of girls shoes to get spring/summer time period ’10.

As overseas education comes with a heavy cost, would the govt consider offering

some kind of interest loan or would liberalise the use of CPF funds for overseas education.

travanj 9, 2013 10:14
 

anonymous said:

Kontroversi Kalvinisme di Inggris, membuahkan Westminster Confession of Faith atau Pengakuan iman Westminster yang dibuat oleh Westminster

Assambly (1643-1649). Caroline kept the style of her youth into later

years. This is a pretty big deal for a couple of

reasons: 1) The whole Non-GMO thing (GMO stands for Genetically Modified Organism…which isn’t really appetizing when we

think of what we want to use to scoop guac) and 2) this oil is

expeller pressed. Edward Norton  fans have had a lot to talk

about over the past few weeks. Utan länk till den rapport som åsyftas

är det lite svårt att skaffa sig en egen mening i frågan men onekligen känns detta som

en artikel som kräver en replik.

travanj 9, 2013 10:16
 

anonymous said:

We have quiet time too…but never called it that – I will now!

In Napo’s opinion, Salix did not hold up its end of the bargain; it filed a lawsuit against the larger company and tried to take back the intellectual property for the drug.

The Soviet Union started its own Psy-warfare superproject and still lost to the

West. Reid La Bruja La Duquesa de Alba La Pequeña La Tigresa La Toya Jackson Lady GaGa Lamar Odom Lana

Del Rey Lance Armstrong Lance Bass Lane Garrison Lara Flynn Boyle Larry Birkhead Larry

King Lauren Pope Laurence Fishburne Lauryn Hill Layla Flaherty

LAZIES Lea Michele LeAnn Rimes Leighton Meester Lena Dunham Lenny Kravitz Leonardo DiCaprio Leslie Carter Let's Hold Hands Levi Johnston Liam Hemsworth Liam Neeson Liberty Ross Liev Schreiber Lil Wayne Lil' Kim Lily Allen Linda Evangelista Linda Perry Lindsay Lohan Lindsay Lohan Lisa Bonet Lisa Lampanelli Lisa Loeb

Lisa Rinna Lisa Turtle Liv Tyler Liz & *** Liza

LL Cool J LMFAO Local News ***-Up Look Who It Is Lorenzo

Martone Love & Handjobs Love Child Luke Perry Lupe Fiasco Lynne Spears M.

I.A. Jay Harrison got a goal back for the Hurricanes

scoring with 40 seconds left after Ward, who finished with 22

saves, was again pulled for an extra attacker.

travanj 9, 2013 10:44
 

anonymous said:

Plan lets to follow fair's course from the wine by something needs and his treasurer, mr. One of the featured regions with a stand of their own will be Brazil's European Valley

, home to scenic towns such as Pomerode and some of the country's best areas for cycling and hiking. Includes exchange rates, Fund accounts and the main global and country economic indicators. When you know the level of insurance you’ll need as well as have looked over your residence for any potential risk factors then it’s time to get some quotations to locate your best home insurance. companies after they work with it for a month in Israel.

travanj 10, 2013 12:25
 

anonymous said:

The author of this article is Robert Tippett. Other minority groups such as Hispanics,

Native-Americans and Asians hardly entered the consciousness

of most Americans. Yeah, they got reported to the EEOC, and I eventually did get a job offer,

but of course I didn't want to work for an employer with that attitude by the time I got the offer. ¡Las encuestas del CEO caen a plomo y desperdigan fragmentos de indefendibles contradicciones! The first time I held him in my arms, I was afraid I’d break him.

travanj 10, 2013 12:32
 

anonymous said:

I like how the green tea and mint give this zesty tea blend a smooth and cleansing finish.

Sigurna sam da su kvalitetna sjenila, ali eto, ove boje

mi nisu toliko jedinstvene da bi bile vrijedne te love.

But if you thought that about the train for the Land of Fall, whoo, I’d not put much

stock in your picking the winners of horse races, or even frog races, for

that matter. Someone has taught you to hate those you do not understand.

As indeed did those 19th and early 20th century Irish nationalists who

insisted on the change in terminology.

travanj 10, 2013 10:10
 

anonymous said:

One of the big reasons I shut down ClearCoin was because that wallet WAS getting big enough

that I'd have to worry a lot more than I wanted to about security.... I recently chose to put on my personal integrity hat, and do my own free investigation of these reports. Harris sued Fannie and Freddie in an effort to further her probe into the mortgage foreclosure practices of Fannie Mae and Freddie Mac. En 1939, la visite de George VI et Elizabeth Bowes-Lyon, motivée par l'imminence de la guerre contre l'Allemagne, est la première d'un monarque anglais sur le sol US.

I will guess the quality of life that a private university has to offer

him is greater.

travanj 10, 2013 10:15
 

anonymous said:

I’m getting real worn out over the Dunne and Moeller act.

Of course, even if Huizar backs the Financial District interests to the hilt, that doesn’t mean the project will die or even lose a vote

at the end of this month. The attack was the latest in a series of so-called "green-on-blue" shootings, in which members of the Afghan security forces have turned their guns on their Western

counterparts. Donkeys and bean eaters are the most relied-upon insults, although

I’ve also heard various parties deem one another their

“slaves” (one insult that, in this post-colonial society

and coming from my race-conscious American society, I

will never feel quite right making, no matter how many times a good-natured Coulibaly tries to

throw that one at me), calling the men of a certain family “couriers de joupons” or womanizers, or saying that

members of the offending family are, in fact, not people. Does she

think that *** is sexy?

travanj 10, 2013 10:15
 

anonymous said:

As a late-war Confederate in the Army of

Northern Virginia, he was adept in drill and marksmanship and was a member of a sharpshooter unit.

While both were generally capable of exceptionally good shooting at long ranges, they served primarily as light infantry in

the classical role of spearheading an attack, guarding a flank, serving as rearguard, or defensively screening their line of

battle. "However, building a successful global brand and organisation requires a lot more than deep pockets -- strong leadership, entrepreneurial managers, consistent strategy, the ability to build trust and ability to manage multi-cultural environments," added IIM alumnus Kamath, who will be a key speaker at

the summit. Without migrant tenants paying rents, it is unclear how long these villagers

will hold out. According to a study published last month in the

journal Health Affairs , I am not the only doctor to have

struggled with transparency and honesty. Repairing

the crimson ring at home is the one in reality practicable choice for anybody who wish

to spend as little cash as possible and make contact with taking section in your favorite video games at once.

travanj 10, 2013 10:49
 

anonymous said:

WARM FRONT FROM 48N 143E TO 47N 147E 46N 151E. The best of the bunch?

فهل يعي سياسيو سنة العراق المطالبين

بإخراج العراق من أحكام البند السابع أنه ليس من مصلحتهم ذلك؟ وأما آن الأوان ليدركوا أن هناك شرخاً عميقاً وواسعاً قد

حصل بين مصلحة العراق ومصلحة السنة، وأن "المشروع الوطني" قد بات خنجراً مسموماً في قلب السنة بعد أن كان في ظهرهم؟).

Indeed, research has shown that women’s innate ability to nurture and

nourish ties, coupled with overall satisfaction with work significantly predicts wellbeing especially during midlife and over the menopausal

transition. Guest40224, ah, well, I don't use Spotify, so I didn't know that was a premium feature.

...

travanj 10, 2013 10:51
 

anonymous said:

I have copied it here so readers could see it.

Science and technologies The day, happening time

in four years, the Intel company chose to declare start of

a series of investment projects in the field of motor industry.

Politics While Teheran continues to threaten the

northern neighbor, and in Baku interrogate the Iranian agents, Pakistan, showing solidarity with Azerbaijan, offered

it alternative to strategic partnership ... The SOCA confirmed

it had arrested the owner of the site, but refused

to tell RT why it is threatening users with a decade behind bars.

Fabio..vc tem toda razão..infelizmente..

travanj 10, 2013 10:59
 

anonymous said:

Attualmente, insegnano presso la Società Sportiva “Body Art” di Manfredonia.

For the next two years Japan would be his home. What is the nation and people interest other than to make

this country a better place to live and to enable the peoples to live in

this country with peace and prosperity? He managed to buy the medicine, but he was covered in blood, and Nagi got it right – he should go to bed.

Coming off an embarrassing 22-20 loss to Cal Poly a week ago, the Bears found themselves in an eerily similar situation Saturday against Utah, trailing 22-20 with just two minutes

left on the clock.

travanj 10, 2013 1:13
 

anonymous said:

After showing me the press, my guide took me to the

library and offered to lend me some of the volumes produced in that monastery during the

last several hundred years. We invite all who can to be with us to experience the transformative power of worshiping community in

the Temple. And then he denied it. You can argue it all you want, but that is not what funding OSPIRG

is. Copyright © 2013 State Supreme Court Initiative.

travanj 10, 2013 1:24
 

anonymous said:

La NASA también ha nominado a 40 científicos estadounidenses para formar parte del Consorcio Euclides, que desarrollará los instrumentos y analizará los datos que genere la misión.

Reilly ). He suffered a torn ACL near the end of spring game.

de cuánto tiempo ha estado viajando la luz de un objeto

a través del Universo, lo que permite determinar en qué momento de la historia del cosmos fue

emitida la luz que ahora detectamos. A travelogue this is not.

travanj 10, 2013 1:58
 

anonymous said:

JUNIE - ID#A023814 My name is JUNIE. So graphics optimization is

an important step in optimizing web page speed. I guess it’s

lucky that all these strange kids are friends with each other and sit together at lunch where

they can all be creepy and overly friendly to our protagonist together.

2) How does an uncomfortable night’s sleep (or

many uncomfortable nights) affect the disposition of people in nursing homes,

particularly those living with dementia? Brian Burke is one of

the biggest assholes I’ve ever had the misfortune

to meet.

travanj 10, 2013 2:17

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server (Commercial Edition), by Telligent Systems