1

I have such common utility class, it looks like this:

public final class Utils {

    public static <T> T forNull(T object, String objectName) {
        if (object == null)
            throw new NullPointerException(String.format("\"%s\" must not be null", objectName));
        return object;
    }

}

...and I'm wondering if it's worthy to move this string -> "\"%s\" must not be null" out of the method and declare it as static final. The method will be used frequently.

2
  • Minor point but i'd use single quotes in your error message. a. it's better grammar and b. it will be less likely to appear as if the object is a String (when it might not be) Commented Aug 10, 2021 at 18:35
  • 2
    You can write this yourself, but it's been done before: Objects.requireNonNull Commented Aug 10, 2021 at 21:15

2 Answers 2

8

Java literal Strings are already cached by the JVM. No matter if this method is executed several times, the string object used through these executions will be the same, so performance won't be an issue.

I would suggest to move such string into a static field if you're going to use that string in several places. This eases maintenance work because you edit the text in a single place rather than in all methods were is used.

Sign up to request clarification or add additional context in comments.

Comments

6

String constants are already deduplicated automatically (it's called "interning"). If the same message is used repeatedly in different contexts, it might make sense to externalize it, but then you have to balance that against separating the format it from its local context.

However, I will provide a frame challenge to your question: Don't have this method at all. The usual recommended approach is not to actively test for null but to let NPEs happen "naturally". Alternately, Objects.requireNonNull already exists, and there's no need to reinvent it.

1 Comment

"The usual recommended approach is not to actively test for null but to let NPEs happen "naturally"." - I think fail-fast is a better approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.