Home > Enterprise >  Why does spring boot libraries like spring-security have assertions in /src/main and not exceptions
Why does spring boot libraries like spring-security have assertions in /src/main and not exceptions

Time:08-18

While going across many modules from spring boot repositories, I could find assertions in /src/main/ like here as below in file,

public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
            Set<String> scopes) {
        super(tokenValue, issuedAt, expiresAt);
        Assert.notNull(tokenType, "tokenType cannot be null");
        this.tokenType = tokenType;
        this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet());
    }

Isn't it should be using exceptions to be thrown instead for all such validations under /src/main/.

As far as I've read, assertions are meant to be used with test cases under /src/test/.

CodePudding user response:

This does throw an exception. The word "assertion" simply means "declare that something should be true", and this can happen in testing or at runtime. You're merging the concepts of assertions in general with the specific tools of the assert keyword in Java or test-assertion libraries like AssertJ.

In this particular case, the Assert in question is org.springframework.util.Assert:

/**
 * Assert that an object is not {@code null}.
 * <pre >Assert.notNull(clazz, "The class must not be null");</pre>
 * @param object the object to check
 * @param message the exception message to use if the assertion fails
 * @throws IllegalArgumentException if the object is {@code null}
 */
public static void notNull(@Nullable Object object, String message) {
    if (object == null) {
        throw new IllegalArgumentException(message);
    }
}

Similar facilities are available with Guava Preconditions and commons-lang Validate; they're not called "assert", but they have identical semantics.

  • Related