Assertion function

버전 1.3.0.1 (1.56 KB) 작성자: Malcolm Wood
A function similar to "assert" in C to assist in bug detection
다운로드 수: 2.3K
업데이트 날짜: 2016/9/1

라이선스 보기

Widely used in languages such as C and (now) Java, assertions are a very useful way of detecting bugs as early as possible in development.
Simply assert in the code that you believe something to be true:
ASSERT(ischar(x) && ~isempty(x),'x is a non-empty string')
If, at runtime, x is not a non-empty string, the ASSERT function throws an error. Using the assertion, rather than waiting for something else to go wrong, guarantees that the problem doesn't go unnoticed, and gives you a meaningful error message.

It also serves as a kind of documentation: when you come back to this code in future to change the way that variable "x" is handled, you can be sure that you don't need to consider the case where "x" is empty or is not a string.

There are two reasons to use ASSERT rather than just using "error" itself.

Firstly, assertions are concise. The above line takes up less space (and arguably is more readable) than:

if ~ischar(x) || isempty(x)
error('x must be a non-empty string');
end

Secondly, when the assertion fails this function shows the message and the current callstack in the MATLAB command window even if the error is caught. By simply using "error", you run the risk that the problem can be hidden by over-zealous error handling code.

Note: The ASSERT function should not be thought of as run-time error detection. You should only assert things are true unless your code contains bugs. An obvious example of when *not* to use an assertion is:
f = fopen('myfile.txt')
ASSERT(f~=-1,'f is a valid file handle'); % do not do this!
This is a valid error condition, and "error" should be used.

Another note: Since R2007a, MATLAB has its own function called "assert", fairly similar to this one. Errors thrown by it aren't automatically shown in the command window, so it could be used for normal run-time error handling, which makes its purpose slightly different from the one supplied here. Take your pick.

인용 양식

Malcolm Wood (2024). Assertion function (https://www.mathworks.com/matlabcentral/fileexchange/10366-assertion-function), MATLAB Central File Exchange. 검색됨 .

MATLAB 릴리스 호환 정보
개발 환경: R14SP3
모든 릴리스와 호환
플랫폼 호환성
Windows macOS Linux
카테고리
Help CenterMATLAB Answers에서 Testing Frameworks에 대해 자세히 알아보기
도움

받음: assert.m

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
버전 게시됨 릴리스 정보
1.3.0.1

Updated license

1.3.0.0

Added copyright notice and discussion of MATLAB's "assert" function.

1.2.0.0

Added copyright line.

1.1.0.0

Review

1.0.0.0