| CIT
594 Example:
Recognizing "if" Statements Spring 2008, David Matuszek |
Consider the following grammar rule:
<if statement> ::= "if" <condition> <block> [ "else" <block> ]
When we write our isIfStatement method, we would like to put this into the
Javadoc for it, so that it looks something like
/**
* Tries to recognize an <if statement>, where:
* <if statement> ::= "if" <condition> <block> [ "else" <block> ]
*/
Unfortunately, if we use this as our Javadoc, it comes out looking like this:
Tries to recognize an , where: ::= "if" [ "else" ]
because Javadoc is turned into HTML, and the characters '<',
'>',
and '&'
are special in HTML. Hence, these characters must be replaced by "<", ">",
and "&", respectively, giving us the much uglier:
/**
* Tries to recognize an <if statement>, where:
* <if statement> ::= "if" <condition> <block> [ "else" <block> ]
*
* @return true If an <if statement> is recognized.
*/
Here is one way of writing the code for
<if statement> ::= "if" <condition> <block> [ "else" <block> ]
public boolean isIfStatement() { |
The above style is probably the easiest to read for correct if statements.
However, it's somewhat difficult to match the error messages up with the
failed tests.
Here is a more compact
version where we check if the required tokens are not present. In
this style it's easy to match up error messages with failed tests, but slightly
harder to follow the flow for correct if statements.
public boolean isIfStatement() { |
In the above, each if statement controls a single statement,
and can be written on a single line. It could be written with braces and
additional lines, as follows:
public boolean isIfStatement() { |
It is generally advisible to write if statements with braces,
even when only a single statement is being controlled, but in this case
I don't think that adds much to the readability of the code. One
advantage, though, is that it's easier to write longer error messages without
getting very long lines.
Any of these styles is perfectly acceptable; really, it's a matter of taste, whichever you find easiest to work with.