Rob Smyth

Tuesday, 24 June 2008

Specific Data Types Avoid Primitives Confusion

An interesting confusion occured today at work one the interpretation of a method parameter named something like 'widgetPercentage'. One developer took 5% as being 0.05 and the original author expected 5% to 5.0. My first thought is that we are missing a 'Percentage' type to remove this ambiguity. But, this would require a constuctor that took a percentage as a sting like 'Percentage("5%")'. Seems fine, but both an example of my loathing of such strings and the lack of use of strong types. I do 'feel' that a strong type could have avoided the problem here.

2 comments:

James said...

Clarity on construction of an object is interesting area because at first and often as a discussion topic it seems so easy.

I was reading the .NET Framework book recently and they had and interesting point on not passing in booleans to set the state of a class. Instead suggesting enums can be more clear.

http://msdn.microsoft.com/en-us/library/ms229039.aspx

For example
string.Compare("Dave", "dave", true)

This would be better.

string.Compare("Dave", "dave", Compare.CaseSensitive)

So in dragging this back to your example would a named constructor or even an exception in the constructor of the class that through on an unlikely decimal value have been useful?

Rob Smyth said...

Hi James,

The thing is that I think it is reasonable for some to consider 0.1 as 10% while others may interpret it as 0.1%. So a constructor taking a decimal or double not (alone) seem useful.

But, your suggestion of an exception would have worked in this case. 0.05 did result in 0.05% which, within the context was unreasonably low. Hmmm ... I want an oportunity to try it out.

Rob