W tym samouczku dowiemy się o instrukcji assert języka Java (asercje Java) na podstawie przykładów.
Asercje w Javie pomagają wykrywać błędy poprzez testowanie kodu, który zakładamy, że jest prawdziwy.
Potwierdzenie jest wykonywane przy użyciu assert
słowa kluczowego.
Jego składnia to:
assert condition;
Tutaj condition
jest wyrażenie boolowskie, które zakładamy, że jest prawdziwe, gdy program jest wykonywany.
Włączanie asercji
Domyślnie potwierdzenia są wyłączone i ignorowane w czasie wykonywania.
Aby włączyć asercje, używamy:
java -ea:arguments
LUB
java -enableassertions:arguments
Gdy asercje są włączone, a warunek jest taki true
, program wykonuje się normalnie.
Ale jeśli warunek zostanie oceniony na, false
gdy asercje są włączone, JVM zgłasza an AssertionError
, a program natychmiast się zatrzymuje.
Przykład 1: Asercja Java
class Main ( public static void main(String args()) ( String() weekends = ("Friday", "Saturday", "Sunday"); assert weekends.length == 2; System.out.println("There are " + weekends.length + " weekends in a week"); ) )
Wynik
W tygodniu są 3 weekendy
Otrzymujemy powyższe dane wyjściowe, ponieważ ten program nie ma błędów kompilacji i domyślnie asercje są wyłączone.
Po włączeniu asercji otrzymujemy następujący wynik:
Wyjątek w wątku „main” java.lang.AssertionError
Inna forma twierdzenia
assert condition : expression;
W tej formie instrukcji asercji wyrażenie jest przekazywane do konstruktora AssertionError
obiektu. To wyrażenie ma wartość, która jest wyświetlana jako szczegółowy komunikat o błędzie, jeśli warunek to false
.
Szczegółowy komunikat służy do przechwytywania i przesyłania informacji o niepowodzeniu potwierdzenia, aby pomóc w debugowaniu problemu.
Przykład 2: Asercja Java z przykładem wyrażenia
class Main ( public static void main(String args()) ( String() weekends = ("Friday", "Saturday", "Sunday"); assert weekends.length==2 : "There are only 2 weekends in a week"; System.out.println("There are " + weekends.length + " weekends in a week"); ) )
Wynik
Wyjątek w wątku "main" java.lang.AssertionError: Są tylko 2 weekendy w tygodniu
Jak widać z powyższego przykładu, wyrażenie jest przekazywane do konstruktora AssertionError
obiektu. Jeśli nasze założenie jest false
i asercje są włączone, zgłaszany jest wyjątek z odpowiednim komunikatem.
Ten komunikat pomaga w diagnozowaniu i naprawianiu błędu, który spowodował niepowodzenie asercji.
Włączanie asercji dla określonych klas i pakietów
Jeśli nie podamy żadnych argumentów do przełączników wiersza polecenia asercji,
java -ea
Umożliwia to asercje we wszystkich klasach z wyjątkiem klas systemowych.
Możemy również włączyć asercję dla określonych klas i pakietów za pomocą argumentów. Argumenty, które można podać do tych przełączników wiersza polecenia, to:
Włącz asercję w nazwach klas
Aby umożliwić asercję dla wszystkich klas naszego programu głównego,
java -ea Main
Aby włączyć tylko jedną klasę,
java -ea:AnimalClass Main
Umożliwia to asercję tylko AnimalClass
w Main
programie.
Włącz asercję w nazwach pakietów
Aby włączyć potwierdzenia tylko dla pakietu com.animal
i jego pakietów podrzędnych,
java -ea:com.animal… Main
Włącz asercję w nienazwanych pakietach
Aby włączyć asercję w nienazwanych pakietach (gdy nie używamy instrukcji pakietu) w bieżącym katalogu roboczym.
java -ea:… Main
Włącz asercję w klasach systemowych
Aby włączyć asercję w klasach systemowych, używamy innego przełącznika wiersza poleceń:
java -esa:arguments
LUB
java -enablesystemassertions:arguments
Argumenty, które można dostarczyć do tych przełączników, są takie same.
Wyłączanie asercji
Aby wyłączyć asercje, używamy:
java -da arguments
LUB
java -disableassertions arguments
To disable assertion in system classes, we use:
java -dsa:arguments
OR
java -disablesystemassertions:arguments
The arguments that can be passed while disabling assertions are the same as while enabling them.
Advantages of Assertion
- Quick and efficient for detecting and correcting bugs.
- Assertion checks are done only during development and testing. They are automatically removed in the production code at runtime so that it won’t slow the execution of the program.
- It helps remove boilerplate code and make code more readable.
- Refactors and optimizes code with increased confidence that it functions correctly.
When to use Assertions
1. Unreachable codes
Unreachable codes are codes that do not execute when we try to run the program. Use assertions to make sure unreachable codes are actually unreachable.
Let’s take an example.
void unreachableCodeMethod() ( System.out.println("Reachable code"); return; // Unreachable code System.out.println("Unreachable code"); assert false; )
Let’s take another example of a switch statement without a default case.
switch (dayOfWeek) ( case "Sunday": System.out.println("It’s Sunday!"); break; case "Monday": System.out.println("It’s Monday!"); break; case "Tuesday": System.out.println("It’s Tuesday!"); break; case "Wednesday": System.out.println("It’s Wednesday!"); break; case "Thursday": System.out.println("It’s Thursday!"); break; case "Friday": System.out.println("It’s Friday!"); break; case "Saturday": System.out.println("It’s Saturday!"); break; )
The above switch statement indicates that the days of the week can be only one of the above 7 values. Having no default case means that the programmer believes that one of these cases will always be executed.
However, there might be some cases that have not yet been considered where the assumption is actually false.
This assumption should be checked using an assertion to make sure that the default switch case is not reached.
default: assert false: dayofWeek + " is invalid day";
If dayOfWeek has a value other than the valid days, an AssertionError
is thrown.
2. Documenting assumptions
To document their underlying assumptions, many programmers use comments. Let’s take an example.
if (i % 2 == 0) (… ) else ( // We know (i % 2 == 1)… )
Use assertions instead.
Comments can get out-of-date and out-of-sync as the program grows. However, we will be forced to update the assert
statements; otherwise, they might fail for valid conditions too.
if (i % 2 == 0) (… ) else ( assert i % 2 == 1 : i;… )
When not to use Assertions
1. Argument checking in public methods
Arguments in public methods may be provided by the user.
So, if an assertion is used to check these arguments, the conditions may fail and result in AssertionError
.
Instead of using assertions, let it result in the appropriate runtime exceptions and handle these exceptions.
2. To evaluate expressions that affect the program operation
Do not call methods or evaluate exceptions that can later affect the program operation in assertion conditions.
Let us take an example of a list weekdays which contains the names of all the days in a week.
ArrayList weekdays = new ArrayList(Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" )); ArrayList weekends= new ArrayList(Arrays.asList("Sunday", "Saturday" )); assert weekdays.removeAll(weekends);
Here, we are trying to remove elements Saturday
and Sunday
from the ArrayList weekdays.
Jeśli asercja jest włączona, program działa poprawnie. Jeśli jednak asercje są wyłączone, elementy z listy nie są usuwane. Może to spowodować awarię programu.
Zamiast tego przypisz wynik do zmiennej, a następnie użyj tej zmiennej do potwierdzenia.
ArrayList weekdays = new ArrayList(Arrays.asList("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" )); ArrayList weekends= new ArrayList(Arrays.asList("Sunday", "Saturday" )); boolean weekendsRemoved = weekdays.removeAll(weekends); assert weekendsRemoved;
W ten sposób możemy zapewnić, że wszystkie weekendy zostaną usunięte z dni powszednich, niezależnie od tego, czy asercja jest włączona, czy wyłączona. Dzięki temu nie ma to wpływu na działanie programu w przyszłości.