- Why Strings are problematic?
- How can we do better?
Stringis ambiguous, because it can represent anythingStringtype provides zero information about structureStringis not self documenting. Future readers have no way of finding all possible valuesStringis not self verifying. The compiler & runtime don't have a way to enforce correct valuesStringproperties discard all the benefits of type safetyStringproperties prevent JVM optimizationStringproperties prevent refactoringStringproperties hinder code maintenanceStringproperties hinder code comprehension
- Always prefer a better type (examples below)
- Include Javadoc with structure assumptions
- Document acceptable characters, including case (eg. use regex)
- Document min & max length (eg. use regex)
- Document nullability
- Include an example
- Enforce structure assumptions using preconditions (eg. use a
Pattern) - Use a clear variable name
- Add a link to any authoritative documentation that would help future readers/maintainers
/**
* Full US Postal zip code:
* [0-9]{5}-[0-9]{4}
*
* eg. "08081-1234"
*/
final String fullZipCode;
/**
* Unique ID within ABC company
* [A-Z0-9]{6}
*
* eg. "1WC45Z"
*/
final String employeeId;
/**
* As defined by RFC2822
*
* eg. "foo@bar.com"
*
* <p>See https://datatracker.ietf.org/doc/html/rfc2822
*/
final String emailAddress;
/**
* Family/Last name
* [A-Za-z- ]{3,32}
*
* eg. "Carmon"
*/
@Nullable
final String lastName;
/**
* RGB hex value
* [0-9a-f]{6} or empty-string (never null)
*
* eg. "00aaff"
*
* <p>See https://en.wikipedia.org/wiki/Web_colors
*/
final String hexColorCode;
/**
* Minimum structure: [0-9-+ ]{12,16}
* Parser imposes more strict structure
*
* eg. "+1 201-404-5555"
*/
final String phoneNumber;booleanfor Strings like"Y"&"N"or"T"&"F"DurationorPeriodfor Strings that look like time periods/durationsGoogle LibPhoneNumberfor Strings containing phone numbers (or just a really clear Javadoc & regex Pattern)Instantfor Strings that look like dates (no timezone info)LocalTimefor Strings that look like times (eg. "When does the meeting start?")longorBigDecimalordoublefor Strings that contain only numbersMapfor Strings that look like key-value pairs (eg."a=5,b=9,...")MonthDayfor Strings with just month and dayOffsetDateTimefor Strings with date-time & timezonePathfor Strings that looks like files/paths/directoriesURIfor Strings that look like urls or resource addressesUUIDfor Strings containing a uuidWeekFieldsorintfor Strings containing a weekYearMonthfor Strings representing year and monthZoneIdorZoneOffsetfor Strings containing timezone info- Enum for bounded set of values
- List or Set for repeated values (eg. comma separated)
charfor Strings that only contain 1 characterintfor Strings containing a year