Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJeremiah Shore
31,168 PointsWhy are phone numbers modeled as integer or long values instead of strings or text in treehouse courses?
From previous studies I have always read or been advised that unless very tight validation is used, or unless there is some mathematical function that needs to be carried out, phone numbers should be modeled as strings or text. I cannot think of any cases where I would need to perform simple math or aggregate functions on one or more phone numbers. Any examination for substrings seems more practical on text anyway. I think this is also more practical for users, as single field phone numbers are often entered with special characters, such as .-,()+ etc.
There are cases where I could see phone numbers being modeled into multiple fields. For example, the North American Numbering Plan has 3 parts: NPA, NXX, and subscriber number. For example, in the number (555) 555-7788, the first 555 is the NPA, the second 555 is the NXX and the 7788 is the subscriber number. There are definite cases where it is valuable to evaluate these separately, especially in the telecommunications industry. However, there is little numeric "meaning" behind these numbers—the values would likely be used for ordering and filtering—and I can't think of any cases where they would need to be anything but strings.
Chris Ramacciotti & Andrew Chalkley , any insight? Just want to make sure I am not missing something.
1 Answer
Chris Ramacciotti
Treehouse Guest TeacherIn Java, storing a phone number as a numeric value (e.g. Long
) means there is inherent validation for numbers. A numeric data type should be sufficient since special characters like dashes and parentheses are for formatting only, and the plusses that precede country codes can be substituted with numeric prefixes instead. However, things might become a little tricky (or at least cumbersome) when dealing with leading zeros, which a Long
would not retain.
Anytime you're choosing a data type, also consider the amount of storage required. Using Java's instrumentation features, I ran a test of storing a 10-digit phone number, both as a String
and as a Long
. The outcomes were identical: 24 bytes for each.
All that said, whatever gives you the most flexibility in your application while ensuring data integrity would be the one you'd choose. If that's a String
, go for it! :)