Plain Java
/**
* USER VALIDATION - PLAIN JAVA
* ----------------------------
* This implementation users only Java.
* It works, but requires:
* - manual null checks
* - manual error handling
* - more boilerplate
*/
package demo;
public class UserValidationPlain {
public static boolean isValid(String username) {
if (username == null) {
throw new IllegalArgumentException("Username must not be null");
}
if (username.isEmpty()) {
throw new IllegalArgumentException("Username must not be empty");
}
if (username.length() < 4) {
return false;
}
return true;
}
}
Guava App
/**
* USER VALIDATION - GUAVA VERSION
* -------------------------------
* This implementation uses Google Guava utilities.
*
* BENEFITS:
* ---------
* - Fail-fast validation
* - Clear intent
* - Less boilerplate
* - Easier to maintain
*/
package demo;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
public class UserValidationGuava {
public static boolean isValid(String username) {
Preconditions.checkArgument(
!Strings.isNullOrEmpty(username),
"Username must not be null or empty"
);
return username.length() >= 4;
}
}
Test
T
/**
* VALIDATION TEST- JUNIT TEST
* ---------------------------
* Same test logic applies to both implementations.
* This highlights that Guava improves code quality, not behavior.
*/
package demo;
import org.junit.Test;
import static org.junit.Assert.*;
public class UserValidationTest {
@Test
public void validUsername() {
assertTrue(UserValidationGuava.isValid("admin"));
}
@Test(expected = IllegalArgumentException.class)
public void nullUsername() {
UserValidationGuava.isValid(null);
}
@Test(expected = IllegalArgumentException.class)
public void emptyUsername() {
UserValidationGuava.isValid("");
}
}