views:

59

answers:

2

I have a simple address object in my domain that has a ToString() method that returns the address like this:

123 Test Ave
Appt 1A
Spokane, WA 99201

We will be diplaying this in a webpage on several different occasions so it makes senses to add the functionality somewhere to display the address with Html formatting, but if I where to add a ToStringHtmlFormat() to my domain class it begins to start to smell funny.

I am probably being a bit picky, but where/how do you suggest accomplishing this to keep my domain class free of any Html stuff?

thanks for you suggestions...

+5  A: 

You could have an HTMLWriter that is able to "Visit" the domain classes and print out the stuff. Your domain classes then need an Accept method to accept the Visitor (Visitor pattern).

In terms of flexibility and maintainability though I would go for some templating engine that contains your HTML and the access to those properties that you want printed out. 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 by UI HTML Engines.

flq
+1 I was never really friends with the visitor pattern, but I agree on having the formatting handled outside the domain classes; formatting is presentation, domain classes are not.
Fredrik Mörk
Thanks for you help!
J.13.L
A: 

You could add an 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 & where the extension method gets included in your project (ex: in your web application only).

Todd Smith