Where to format data meant for display?

Topics: Prism v2 - WPF 3.5
Feb 6, 2010 at 10:07 AM

I was having a discussion with one of my colleagues the other day about where to format (simple) data meant for display.

Let's say I have an external source, which returns a floating point value. I use a service to fetch that value from the external source. On my view I have 2 text blocks where I'd like to show that value, one with 2 digits behind the decimal sign, one with 4 digits behind the decimal sign. My colleague insists that the formatting should happen in my service, hence creating 2 properties which return the formatted value. This feels wrong to me. If I want to display this value in 10 different ways this means I have to create 10 properties with silly names such as DataWith2DigitsBehindDecimalSign, DataWith4DigitsBehindDecimalSign. To me it seems more logical to use 1 property which simply returns the floating point value and format the data in the property where the view binds to.

If this service is used by multiple views and all of those views display the data in the same way, then I would be OK with adding a property which returns the proper formatted data, but even then I would still prefer to do it per view as this would give me greater control to modify a single display later on.

Is there a proper way of doing this, if so, which one is it?

Thanks.

Feb 11, 2010 at 1:50 PM

Hi,

This topic is something that does not have a right answer, but I’ll express my point of view hoping it can be of help.

As you said, having the formatting done in the service that retrieves the value is an unnecessary overhead for the service’s interface, as it should only care on returning the value. Formatting the number is specifically related to the presentation layer of your application, so it should be done there instead of the business logic of your application which is where the service works.

In my personal opinion, taking advantage of WPF ValueConverters would be the way to go here. This way, the service only gets the required information and the properties always hold the same value. You simply change the ValueConverter associated to the binding to get the different formats.

Another approach could be a “formatting service” that lives in the presentation layer, and is in charge of formatting the numbers before they are exposed by properties in the ViewModel for the View to bind to.

One possible case when providing multiple service methods to get more/less precision from the service is a viable approach is if getting a value with more resolution takes considerably more time than without it. That way, if you don’t actually need the extra numbers you can save the extra time.

Please let me know if this helps.

Damian Schenkelman
http://blogs.southworks.net/dschenkelman