Trong hướng dẫn này, chúng ta sẽ tìm hiểu về câu lệnh khẳng định Java (Java khẳng định) với sự trợ giúp của các ví dụ.
Các xác nhận trong Java giúp phát hiện lỗi bằng cách kiểm tra mã mà chúng tôi cho là đúng.
Một khẳng định được thực hiện bằng cách sử dụng assert
từ khóa.
Cú pháp của nó là:
assert condition;
Đây condition
là một biểu thức boolean mà chúng tôi giả sử là đúng khi chương trình thực thi.
Kích hoạt khẳng định
Theo mặc định, các xác nhận bị tắt và bị bỏ qua trong thời gian chạy.
Để bật xác nhận, chúng tôi sử dụng:
java -ea:arguments
HOẶC LÀ
java -enableassertions:arguments
Khi các xác nhận được kích hoạt và điều kiện là true
, chương trình sẽ thực thi bình thường.
Nhưng nếu điều kiện được đánh giá là false
trong khi các xác nhận được bật, JVM sẽ ném một dấu AssertionError
và chương trình dừng ngay lập tức.
Ví dụ 1: Khẳng định 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"); ) )
Đầu ra
Có 3 ngày cuối tuần trong một tuần
Chúng tôi nhận được kết quả ở trên vì chương trình này không có lỗi biên dịch và theo mặc định, các xác nhận bị vô hiệu hóa.
Sau khi bật xác nhận, chúng tôi nhận được kết quả sau:
Ngoại lệ trong luồng "main" java.lang.AssertionError
Một dạng tuyên bố khẳng định khác
assert condition : expression;
Trong dạng câu lệnh khẳng định này, một biểu thức được chuyển tới hàm tạo của AssertionError
đối tượng. Biểu thức này có một giá trị được hiển thị dưới dạng thông báo chi tiết của lỗi nếu điều kiện là false
.
Thông báo chi tiết được sử dụng để nắm bắt và truyền thông tin về lỗi xác nhận để giúp gỡ lỗi vấn đề.
Ví dụ 2: Khẳng định Java với ví dụ về biểu thức
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"); ) )
Đầu ra
Ngoại lệ trong luồng "main" java.lang.AssertionError: Chỉ có 2 ngày cuối tuần trong một tuần
Như chúng ta thấy từ ví dụ trên, biểu thức được chuyển cho hàm tạo của AssertionError
đối tượng. Nếu giả định của chúng tôi là false
và xác nhận được kích hoạt, một ngoại lệ sẽ được đưa ra với một thông báo thích hợp.
Thông báo này giúp chẩn đoán và sửa lỗi khiến xác nhận không thành công.
Bật xác nhận cho các lớp và gói cụ thể
Nếu chúng tôi không cung cấp bất kỳ đối số nào cho các công tắc dòng lệnh khẳng định,
java -ea
Điều này cho phép xác nhận trong tất cả các lớp ngoại trừ các lớp hệ thống.
We can also enable assertion for specific classes and packages using arguments. The arguments that can be provided to these command-line switches are:
Enable assertion in class names
To enable assertion for all classes of our program Main,
java -ea Main
To enable only one class,
java -ea:AnimalClass Main
This enables assertion in only the AnimalClass
in the Main
program.
Enable assertion in package names
To enable assertions for package com.animal
and its sub-packages only,
java -ea:com.animal… Main
Enable assertion in unnamed packages
To enable assertion in unnamed packages (when we don’t use a package statement) in the current working directory.
java -ea:… Main
Enable assertion in system classes
To enable assertion in system classes, we use a different command-line switch:
java -esa:arguments
OR
java -enablesystemassertions:arguments
The arguments that can be provided to these switches are the same.
Disabling Assertions
To disable assertions, we use:
java -da arguments
OR
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.
Nếu xác nhận được bật, chương trình hoạt động tốt. Tuy nhiên, nếu các xác nhận bị tắt, các phần tử từ danh sách sẽ không bị xóa. Điều này có thể dẫn đến lỗi chương trình.
Thay vào đó, hãy gán kết quả cho một biến và sau đó sử dụng biến đó để khẳng định.
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;
Bằng cách này, chúng tôi có thể đảm bảo rằng tất cả các ngày cuối tuần đều được xóa khỏi các ngày trong tuần bất kể xác nhận được bật hay tắt. Nhờ vậy, nó không ảnh hưởng đến hoạt động của chương trình sau này.