Re: About using assertion
On 9 Mai, 16:36, byhesed <byhe...@gmail.com> wrote:
I am reading a book about object-oriented design pattern.
The book, Object-Oriented Software Development Using Java 2/e by
Xiaoping Jia, says that...
=E3=80=80=E3=80=80=E3=80=80=E3=80=80Using assertions derived from the pre=
conditions for all methods is
known as defensive programming.
=E3=80=80=E3=80=80=E3=80=80=E3=80=80Its aim is to prevent a component fro=
m being misused.
=E3=80=80=E3=80=80=E3=80=80=E3=80=80Design Guideline: Use Assertions Aggr=
essively
=E3=80=80=E3=80=80=E3=80=80=E3=80=80Each method should include assertions=
on the preconditions and
postconditions of the method and invariants of the class
Do I have to always use assertion?
Is it better to use assertion?
What's your idea?
Expressions after "assert" are only evaluated if assertions are
explicitly enabled for the class. The idea is to be able to activate
it during testing to ensure components work as designed and have it
switched off during production in order to gain better performance
(assertion checks could be costly).
Having said that I'd say that argument checking is probably more
important than assertions. Whether to use assertions or not depends a
lot on the nature and complexity of the class. I also often find it
useful to have a method with boolean return value called
classInvariant() which will check a class's invariant. You can then
call that from multiple locations (e.g. entering a method, leaving a
method).
In short: assertions are a good - when not overused.
Kind regards
robert