Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code business logic or presentation logic?

Tags:

c#

asp.net-mvc

This code exists in a View:

       if (Model.Group.IsPremium && null != Model.Group.ContactInfo)
       {
           Html.RenderPartial("ContactInfo", Model.Group.ContactInfo);
       }

at first glance, it's presentation logic and so it's ok. But it's not sitting well with me.

The thing is, it's a business requirement to display contact info if the group is classified as premium, which means they paid.

What do you guys think? Should this logic be moved into a HtmlHelper or abstracted away by some other means? Or is this the intended usage of the View? What's the best thing to do with this code?

like image 883
DaveDev Avatar asked Dec 28 '22 09:12

DaveDev


2 Answers

I'd produce a ViewModel that encapsulates this logic as a boolean DisplayContactInfo property. It depends on how "clean" you want your views.

like image 104
Darren Lewis Avatar answered Jan 12 '23 16:01

Darren Lewis


I would definitely move this into a ViewHelper. This is so because once you start writing view logic in the views - aspx files - you start creating 'tag soup' which decreases code understandability and thus increases maintenance cost.

Another benefit of using ViewHelpers to encapsulate your view logic is that it also makes your application more pliable to unit testing. So given your above code I would use it in a ViewHelper like so,

using System.Linq;
using System.Web.Mvc;
using System;
using System.Text;
using System.Web.Mvc.Html; //Need this for Html helper extension method

public static class GroupViewHelper
{
    public static void ShowContactInfo(this HtmlHelper helper, ModelType model)
    {
        if (model.Group.IsPremium && null != model.Group.ContactInfo)
        {
            //Do your rendering here.
        }
    }

   // ... your other ViewHelper methods here.
}

Subsequently, somewhere in your view, I would call this helper method like so,

<% Html.ShowContactInfo(Model); %>

This technique results in views which avoid the 'tag soup', are more maintainable and immensely unit testable.

like image 20
Bikal Lem Avatar answered Jan 12 '23 16:01

Bikal Lem