У овом упутству ћемо научити о Јава изјави за потврђивање (Јава тврдње) уз помоћ примера.
Тврдње у Јави помажу у откривању грешака тестирањем кода за који претпостављамо да је истинит.
Тврдња се износи помоћу assert
кључне речи.
Његова синтакса је:
assert condition;
Овде condition
је логички израз за који претпостављамо да је истинит када се програм извршава.
Омогућавање тврдњи
Тврдње су подразумевано онемогућене и игнорисане током извођења.
Да бисмо омогућили тврдње, користимо:
java -ea:arguments
ИЛИ
java -enableassertions:arguments
Када су тврдње омогућене и услов је true
, програм се извршава нормално.
Али ако се услов процени false
док су тврдње омогућене, ЈВМ баца знак AssertionError
и програм се одмах зауставља.
Пример 1: Јавна тврдња
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"); ) )
Оутпут
Постоје 3 викенда у недељи
Горе наведени излаз добијамо јер овај програм нема грешака у компилацији и по подразумеваној вредности су тврдње онемогућене.
Након омогућавања тврдњи, добивамо следећи излаз:
Изузетак у нити "маин" јава.ланг.АссертионЕррор
Други облик изјаве о тврдњи
assert condition : expression;
У овом облику изјаве о тврдњи, израз се преноси конструктору AssertionError
објекта. Овај израз има вредност која се приказује као порука са детаљима грешке ако је услов такав false
.
Детаљна порука се користи за хватање и пренос информација о неуспеху тврдње да би помогла у решавању проблема.
Пример 2: Јавна тврдња са примером израза
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"); ) )
Оутпут
Изузетак у нити "маин" јава.ланг.АссертионЕррор: Постоје само 2 викенда у недељи
Као што видимо из горњег примера, израз се преноси конструктору AssertionError
објекта. Ако је наша претпоставка false
и тврдње омогућене, изузетак се шаље одговарајућом поруком.
Ова порука помаже у дијагностиковању и исправљању грешке која је проузроковала да тврдња пропадне.
Омогућавање тврдњи за одређене класе и пакете
Ако не дамо никакве аргументе прекидачима командне линије за тврдњу,
јава -еа
Ово омогућава тврдње у свим класама осим системских класа.
Такође можемо омогућити тврдњу за одређене класе и пакете користећи аргументе. Аргументи који се могу пружити овим прекидачима командне линије су:
Омогућите тврдњу у именима класа
Да бисмо омогућили тврдњу за све класе нашег програма Маин,
java -ea Main
Да бисте омогућили само једну класу,
java -ea:AnimalClass Main
Ово омогућава тврдњу само AnimalClass
у Main
програму.
Омогућите тврдњу у именима пакета
Да бисте омогућили тврдње само за пакет com.animal
и његове подпакете,
java -ea:com.animal… Main
Омогућите тврдњу у неименованим пакетима
Да бисте омогућили тврдњу у неименованим пакетима (када не користимо изјаву о пакету) у тренутном радном директоријуму.
java -ea:… Main
Омогућите тврдњу у системским класама
Да бисмо омогућили тврдњу у системским класама, користимо другачији прекидач командне линије:
java -esa:arguments
ИЛИ
java -enablesystemassertions:arguments
Аргументи који се могу пружити овим прекидачима су исти.
Онемогућавање тврдњи
Да бисмо онемогућили тврдње, користимо:
java -da arguments
ИЛИ
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.
Ако је тврдња омогућена, програм ради у реду. Међутим, ако су тврдње онемогућене, елементи са листе се неће уклонити. То може довести до неуспеха програма.
Уместо тога, доделите резултат променљивој, а затим је користите за потврђивање.
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;
На овај начин можемо осигурати да се сви викенди уклоне из радних дана, без обзира на то да ли је нека тврдња омогућена или онемогућена. Као резултат, то не утиче на рад програма у будућности.