In questo tutorial, impareremo a conoscere la dichiarazione di asserzione Java (asserzioni Java) con l'aiuto di esempi.
Le asserzioni in Java aiutano a rilevare i bug testando il codice che presumiamo sia vero.
Un'asserzione viene effettuata utilizzando la assert
parola chiave.
La sua sintassi è:
assert condition;
Ecco condition
un'espressione booleana che assumiamo essere vera quando il programma viene eseguito.
Abilitazione delle asserzioni
Per impostazione predefinita, le asserzioni sono disabilitate e ignorate in fase di esecuzione.
Per abilitare le asserzioni, utilizziamo:
java -ea:arguments
O
java -enableassertions:arguments
Quando le asserzioni sono abilitate e la condizione è true
, il programma viene eseguito normalmente.
Ma se la condizione restituisce false
mentre le asserzioni sono abilitate, JVM genera un AssertionError
e il programma si interrompe immediatamente.
Esempio 1: asserzione 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"); ) )
Produzione
Ci sono 3 fine settimana in una settimana
Otteniamo l'output di cui sopra perché questo programma non ha errori di compilazione e per impostazione predefinita, le asserzioni sono disabilitate.
Dopo aver abilitato le asserzioni, otteniamo il seguente output:
Eccezione nel thread "main" java.lang.AssertionError
Un'altra forma di dichiarazione di asserzione
assert condition : expression;
In questa forma di dichiarazione di asserzione, un'espressione viene passata al costruttore AssertionError
dell'oggetto. Questa espressione ha un valore che viene visualizzato come messaggio di dettaglio dell'errore se la condizione è false
.
Il messaggio dettagliato viene utilizzato per acquisire e trasmettere le informazioni sull'errore di asserzione per facilitare il debug del problema.
Esempio 2: asserzione Java con esempio di espressione
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"); ) )
Produzione
Eccezione nel thread "main" java.lang.AssertionError: ci sono solo 2 fine settimana in una settimana
Come si vede dall'esempio precedente, l'espressione viene passata al costruttore AssertionError
dell'oggetto. Se la nostra ipotesi è false
e le asserzioni sono abilitate, viene generata un'eccezione con un messaggio appropriato.
Questo messaggio aiuta a diagnosticare e correggere l'errore che ha causato il fallimento dell'asserzione.
Abilitazione dell'asserzione per classi e pacchetti specifici
Se non forniamo alcun argomento alle opzioni della riga di comando dell'asserzione,
java -ea
Ciò abilita le asserzioni in tutte le classi eccetto le classi di sistema.
Possiamo anche abilitare l'asserzione per classi e pacchetti specifici usando gli argomenti. Gli argomenti che possono essere forniti a queste opzioni della riga di comando sono:
Abilita l'asserzione nei nomi delle classi
Per abilitare l'asserzione per tutte le classi del nostro programma Main,
java -ea Main
Per abilitare solo una classe,
java -ea:AnimalClass Main
Ciò consente l'asserzione solo AnimalClass
nel Main
programma.
Abilita l'asserzione nei nomi dei pacchetti
Per abilitare le asserzioni solo per il pacchetto com.animal
e i suoi sotto-pacchetti,
java -ea:com.animal… Main
Abilita l'asserzione nei pacchetti senza nome
Per abilitare l'asserzione nei pacchetti senza nome (quando non usiamo un'istruzione del pacchetto) nella directory di lavoro corrente.
java -ea:… Main
Abilita asserzione nelle classi di sistema
Per abilitare l'asserzione nelle classi di sistema, utilizziamo un'opzione della riga di comando diversa:
java -esa:arguments
O
java -enablesystemassertions:arguments
Gli argomenti che possono essere forniti a queste opzioni sono gli stessi.
Disattivazione delle asserzioni
Per disabilitare le asserzioni, utilizziamo:
java -da arguments
O
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.
Se l'asserzione è abilitata, il programma funziona correttamente. Tuttavia, se le asserzioni sono disabilitate, gli elementi dall'elenco non vengono rimossi. Ciò potrebbe causare un errore del programma.
Assegnare invece il risultato a una variabile e quindi utilizzare quella variabile per l'asserzione.
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;
In questo modo, possiamo garantire che tutti i fine settimana vengano rimossi dai giorni feriali indipendentemente dall'attivazione o disattivazione dell'asserzione. Di conseguenza, non influisce sul funzionamento del programma in futuro.