Guard Clauses
Part of the Logic & Flow section of Coddy's Java journey — lesson 38 of 59.
Guard clauses are conditional statements at the beginning of a method that check for invalid conditions and return early. They help make code cleaner and more readable by handling edge cases first.
Let's see a method without guard clauses:
public int divide(int num, int den) {
if (den != 0) {
if (num >= 0) {
return num / den;
} else {
return -1;
}
} else {
return -1;
}
}The same method with guard clauses:
public int divide(int num, int den) {
if (den == 0) return -1;
if (num < 0) return -1;
return num / den;
}After executing either code with divide(10, 2), the result is:
5
Challenge
EasyCreate a method named validatePassword that takes one argument:
- A String (
password) to validate
The method should use guard clauses to validate the password and return a message string based on these rules:
- If password is null: return "Password cannot be null"
- If password is empty: return "Password cannot be empty"
- If password length is less than 8: return "Password must be at least 8 characters"
- If password contains spaces: return "Password cannot contain spaces"
- If all checks pass: return "Valid password"
Cheat sheet
Guard clauses are conditional statements at the beginning of a method that check for invalid conditions and return early, making code cleaner and more readable.
Without guard clauses:
public int divide(int num, int den) {
if (den != 0) {
if (num >= 0) {
return num / den;
} else {
return -1;
}
} else {
return -1;
}
}With guard clauses:
public int divide(int num, int den) {
if (den == 0) return -1;
if (num < 0) return -1;
return num / den;
}Try it yourself
import java.util.Scanner;
public class Main {
public static String validatePassword(String password) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String password = scanner.nextLine();
if (password.equals("null")) {
password = null;
}
System.out.println(validatePassword(password));
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap3HashMap Part 2
HashMap MethodsIterate with keySet()Iterate with entrySet()Nested HashMapRecap - Manage WarehouseRecap - HashMap Operations6Advanced Control Flow
Label StatementsSwitch ExpressionPattern MatchingGuard ClausesRecap - Control Flow