Do we have to approve every object creation in java?

Sounds a dumb question with an obvious answer :)

Nevertheless, I ventured to ask you to be doubly sure.

We really use the statements below.

ArrayList alProperties = new ArrayList();

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

The problem is that creating a small and simple document to follow is difficult. There are many books on statements, but ideally I would like to give the new programmer very simple recommendations on using something like statements. Btw, is there any tool like pmd for using assertions correctly?

Thanks in advance.

+3
source share
9 answers

. - , assert ( , , VM)

+19

Sun . , , , , .

+6

, .

, jvm OutOfMemoryError, , , , .

+4

JVM. , , -...

+3

Java new , . , , catch.

, Java, assert. . assert , (, , , ).

+3

, :

boolean a = true;
assert a : "A should be true"

JVM, (, JVM). , - . .

, , ( , , ).

- , , , sqrt sqrt, , , , ( , ). .

, , (. ) - . .

, assert, , , ArrayList.Create(), null. , . , ( ) factory.

int max(int[] a, int n) {
  assert n <= a.length : "N should not exceed the bounds of the array"
  assert n > 0 : "N should be at least one"

  // invariant: m is the maximum of a[0..i]
  int m = a[0];
  for( int i = 1; i < n; n++ ) {
    if( m < a[i] )
      m = a[i];
  }

  // if these were not basic types, we might assert that we found
  // something sensible here, such as m != null
  return m;
}
+3

, , , .

, , .

+1

, ASSERTS . .

0

, , , .

, , , , , , , !

0

Source: https://habr.com/ru/post/1712190/


All Articles