Friday, October 19, 2007

Strings - The only data type you will ever need.

I have seen lots of code that looks like the following

Person candidate = CreatePerson()
string hireDate= "02/12/2005"
string departmentId = "12";

I often see methods that take strings as parameters when they are dealing with values that should be stored in more expressive data types. Usually this happens with values that get pulled out of text boxes on the UI. These parameters start getting pasted all over the place and only end up getting cast to a more specific data type when some special functionality like date comparison is needed.I have also seen this happen with id values. They often get converted back and forth from int to string as they get passed around the application. I guess this code smell is kind of like primitive obsession taken to the extreme.


Chris Barrow said...

I certainly don't think it's an obsession. It is simply good practice to enforce data types within methods. Using strings is simply a lazy approach, but in the end it will cause you more problems than it will solve.

Englestone said...

What's even more fun is when you find all manner of dates and numbers stored as strings in a database.. :-(

I unfortunately have the mispleasure of dealing this reality on a daily basis :(

-- Lee