These aren't the types you're looking for
When adding a property to an object meant to contain text, you usually just declare it as
string without giving it a second thought. Here though, I’m asking you to give it a second thought, as others did before me and came to the same conclusion: there’s a better way.
If not string, then what?
Let’s say instead of
string you declare all your properties containing text as
object. At this point you’re probably thinking about all the reasons why
string is a way more appropriate type than
objectis too general and accepts things that are not valid for this property
objectdoes a poor job at documenting what’s valid for this property
objectbeing too general means validation and error handling code is going to be necessary throughout the solution
If you agree with the above, you’re already halfway through this journey, and I’m going to prove it to you with a concrete example. Let’s say the property we’re adding is ‘author’ containing an email. Email is text, and as we just saw
object is not a good choice, so let’s consider using
string instead, and just to be thorough let’s let’s replace
string in the above 3 reasons and see what they look like:
stringis too general and accepts things that are not valid for this property
stringdoes a poor job at documenting what’s valid for this property
stringbeing too general means validation and error handling code is going to be necessary throughout the solution
Wait, what? They’re all still true!
stringis too general because there’s a myriad of things that are strings and aren’t valid emails, in fact most strings aren’t emails
stringdoes little to document the property, a
stringauthor could just as well be a first and last name combination
stringis never guaranteed to be an email until you actively validate its content, in fact, it’s not even guaranteed to have any characters in it
So it turns out that
string is only marginally better than
object, and that’s why…
…these aren’t the types you’re looking for
So what are the types that I’m looking for? — you may or may not ask depending on whether you made it this far into the article. The answer is simple, but its implementation may vary from straightforward to downright unwieldy depending on your choice of programming language and libraries. This article is only meant to open your mind about something we as programmers have been doing for ages without ever realizing that there’s a better way. In the next post I’ll explore this better way so do follow me on twitter to be notified when it’s up.