Forming html in domain classes

I have a simple address object in my domain that has a method ToString()

that returns an address like this:

123 Test Ave
Appt 1A
Spokane, WA 99201

We'll be discussing this on the web page on a couple of different occasions so that it can add functionality somewhere to display an address with Html formatting, but if I add it ToStringHtmlFormat()

to my domain class it starts to start smelling funny.

I'm probably a little picky, but where / how do you suggest doing this so that my domain class doesn't contain any Html stuff?

thanks for your suggestions ...

+1


a source to share


2 answers


You can have an HTMLWriter that can "visit" the domain's classes and print stuff. Then your domain classes need to accept an Accept method to accept a visitor (visitor pattern).



In terms of flexibility and maintainability though I would go for some kind of templating engine containing your HTML and access to whatever properties you want to print. Often, more complex sites will also introduce something called a ViewModel, which prepares the data to be displayed in a way that is easily accessible using HTML UI engines.

+6


a source


You can add extension method:

public static class AddressHelpers
{
  public static string ToStringHtmlFormat (this Address address)
  {
      string result = address.Address1;
      // snip..
      return result;
  }
}

      



and now you can control when and where the extension method will be included in your project (ex: only in your web application).

+1


a source







All Articles