jeudi 21 janvier 2016

Inheritance in combination with class Attribute parameters

Question is for educational purposes only.

I have MVC application that has 3 Web Journeys that mirror one another in many ways - which makes it convenient to introduce Base class that would take care of common parts.

I am also using lots of class attributes that are being put into viewData this makes it convenient when reusing the views between journeys where I can insert different phone number (or other bits) per journey without need to inherit this data in each viewModel, as it is same per journey (not placeable into master page as it is shown in many different views). These constants also are used in code when generating emails and such.

[LayoutViewData(ContactNumber = ContactNumber, LegalType = LegalType, LegalReference = LegalReference)]
public class JourneyController : BaseJourneyController
{
    private const string ContactNumber = "0800 161 5191";
    private const string ContactNumberForPricingPage = "0800 051 3322";
    private const string ProductReference = "LS0083";
    private const string LegalReference = "conveyancing";
}


public class LayoutViewDataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewData.Add("ContactNumber", this.ContactNumber);
    }
    ...
}

Problem that I am trying to solve:

There are methods that are almost identical in journeys and could be moved to base but they require values from constants. Problem is that only statics can be passed into attributes, which means I cannot simply change them to abstract properties with getters only and move on with my life.

My options:

  1. Change method signatures to pass these constants into method - I don't like this since having to pass data to base indicates that implementation should be in class itself.

  2. Introduce abstract Get methods that would then return constants for use in base class eg.

    protected override string GetContactNumber()
    {
        return ContactNumber;
    }
    
    

    I don't like that there is no way to force to return those specific constants and feels a bit hacky, yet IMHO best solution for least amount of effort.

  3. Get rid of constants and attributes and introduce BaseViewModel class that would have abstract properties and one mechanism per journey that would set there values. Or could be 3 base classes with those properties already set. - don't like it, lots of replacements.

Can you think of some other solution that would be minimum work and minimum hacks that would solve my situation.

Aucun commentaire:

Enregistrer un commentaire