Search code examples
javastringspring-bootstring-formattingtrim

Java trim() : Cleanest way to check null string before trimming?


I use trim() method in order to trim leading and trailing whitespaces in some of the string field.

siteRequest.getName().trim();

However, when string field is null, it throws exception as expected. I can check the values before trimming as shown below:

siteRequest.getName() ? siteRequest.getName() : siteRequest.getName().trim();

However, if it is possible I would prefer a cleaner way so that several people had already faced this problem. Any suggestion with a smarter approach?


Solution

  • I like the idea from @Sebastiaan van den Broek but would prefer not to use the library and therefore look up its implementation:

    // Trim
    //-----------------------------------------------------------------------
    /**
     * <p>Removes control characters (char &lt;= 32) from both
     * ends of this String, handling {@code null} by returning
     * {@code null}.</p>
     *
     * <p>The String is trimmed using {@link String#trim()}.
     * Trim removes start and end characters &lt;= 32.
     * To strip whitespace use {@link #strip(String)}.</p>
     *
     * <p>To trim your choice of characters, use the
     * {@link #strip(String, String)} methods.</p>
     *
     * <pre>
     * StringUtils.trim(null)          = null
     * StringUtils.trim("")            = ""
     * StringUtils.trim("     ")       = ""
     * StringUtils.trim("abc")         = "abc"
     * StringUtils.trim("    abc    ") = "abc"
     * </pre>
     *
     * @param str  the String to be trimmed, may be null
     * @return the trimmed string, {@code null} if null String input
     */
    public static String trim(final String str) {
        return str == null ? null : str.trim();
    }
    

    From my point of view there is no better way to implement it. Using Optionals is not an option. Therefore, the original solution idea in the question is confirmed.