- How to build a proper utility class in Java 8+
- You are probably reinventing the wheel :-)
- Verify Core Java, Apache Commons, Guava & Spring lack what you're building
ArithmeticUtilsBagUtilsBeanUtilsBooleanUtilsCaseUtilsClassUtilsCollectionUtilsComparatorUtilsConvertUtilsDbUtilsDigestUtilsFileUtilsIOUtilsKeyManagerUtilsListUtilsMapUtilsMathUtilsMethodUtilsMimeMessageUtilsObjectUtilsPropertyUtilsSSLContextUtilsStringEscapeUtilsStringUtilsSystemUtilsTrieUtilsTrustManagerUtilsWordUtils
AtomicsBooleansByteStreamsCharsCloseablesDoublesEscapersFilesFlushablesGraphsInetAddressesIntsIterablesIteratorsListsLongsMapsMoreExecutorsMoreFilesMultimapsMultisetsObjectArraysPreconditionsPrimitivesQueuesRunnablesSetsStatsStringsTablesUninterruptiblesUrlEscapers
AnnotationUtilsBase64UtilsBeanUtilsClassUtilsDataSourceUtilsDomUtilsFileSystemUtilsMimeTypeUtilsReflectionTestUtilsSystemPropertyUtilsUriUtilsValidationUtils
- Add brief javadoc, with a summary of purpose
- Document who is responsible for closing resources (like IO Streams)
Caller is responsibleorcallee is responsible
- Mark the utility class
final
- No instance properties on the utility class
static finalconstants are acceptable (at top of file)
- Package name: ends with
.util;(Eg.com.abc.util) - Class name: ends with
Utils(eg. see Apache commons examples above)- Core Java & Guava tend to name utils after a Type (eg.
Fooscontains methods to simplify usingFoo) - Apache Commons and Spring tend to name utilities with the
Utilssuffix - Avoid naming collisions by using the
Utilssuffix (and not reinventing the wheel)
- Core Java & Guava tend to name utils after a Type (eg.
privateconstructor- Exactly one constructor
- constructor accepts zero arguments
- Length: Less than 75-lines per method
- Args: Add Preconditions on method args (unless they are nullable)
- All methods must be
static - Use method signatures consistent with other popular utilities (Apache Commons, Guava, ...)
- Ensure all methods are Stateless
- Ensure all methods are threadsafe
- Three arguments max. Accept a POJO if you need mor args.
- Never mutate method Arguments
- Add "enough" tests to exercise both positive and negative cases
- Lenient in args, Strict on output
- Use modern types
- no hard coded dates, pass clock