0

I am new to Java and I am trying to understand how to design a circuit using Java. I found this piece of code:

Can somebody explain why asset is used:

Here's example:

 assert(list.length == 2); 

Thanks

Delimitry
  • 2,987
  • 4
  • 30
  • 39
  • 2
    You may want to read a book or tutorial about Java. Or maybe just search on Internet... – Christian Tapia Dec 27 '13 at 17:14
  • You could have simply googled: "Java assert". – Martijn Courteaux Dec 27 '13 at 17:17
  • Also note that the original code you posted is bad practice. Oracle tells you not to use assert to check public method parameters (http://www.oracle.com/us/technologies/java/assertions-139853.html). That should throw an Exception instead of killing the program. They say: *Note: Because assertions might be disabled in some cases, precondition checking can still be performed by checks inside methods that result in exceptions such as IllegalArgumentException or NullPointerException.* – Martijn Courteaux Dec 27 '13 at 17:24
  • how can i change it not to use assert? – user3125044 Dec 27 '13 at 17:27

2 Answers2

2

assert is a precondition. That is, the method is checking that it's been called correctly (with 2 arguments) before it actually performs any logic. This is a common pattern (not common enough, I would argue) to determine that code is being used correctly. You may see postconditions too, which assert that the method is returning a valid result (e.g. not null or similar)

The second line performs an AND action (&&) on the 2 arguments - i.e. it performs the actual logic required.

I'm surprised that the interface permits multiple arguments to be passed to the gate (multiple inputs) but the method only uses 2 arguments. You could easily AND through all the arguments (in which case you could avoid the assertion completely)

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
0

assert(...) just means that if the expression inside the parenthesis is true, it does nothing. If the expression is false, it throws an error. Basically, when false, it is telling whoever is calling this 'ope' method that they are giving it too few or too many inputs.

An 'and' gate does just what you think. It returns true if both inputs are true, and false if either of them are false. The return statement just performs the 'and' (&&) operation on the two inputs, as expected.

user2503846
  • 924
  • 1
  • 7
  • 10