Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we assert every object creation in java?

Sounds like a stupid question with an obvious answer :)

Still I've ventured to ask just be doubly sure.

We are indeed using asserts like given below

ArrayList alProperties = new ArrayList();

assert alProperties != null : "alProperties is null";

Problem is that making a small & simple document to follow, on asserts is difficult. There are many books on asserts, but ideally I like to give a new programmer very simple guidelines on using something like asserts. Btw, does some tool like pmd check for proper usage of asserts?

Thanks in advance.

like image 650
amolkul Avatar asked Nov 27 '22 23:11

amolkul


2 Answers

There's no sane reason to use asserts like that. If the object won't be created for some reason, your assert won't even be reached (because an exception was thrown or the VM exited, for example)

like image 162
Jorn Avatar answered Jan 01 '23 17:01

Jorn


There are some fairly concise guidelines on using assertions in Sun's Programming with Assertions. That article advises that asserts should be used for things like Internal Invariants, Control-Flow Invariants, and Preconditions, Postconditions, and Class Invariants.

like image 39
Bill the Lizard Avatar answered Jan 01 '23 18:01

Bill the Lizard