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 &lt;if statement&gt;, where:
* &lt;if statement&gt; ::= "if" &lt;condition&gt; &lt;block&gt; [ "else" &lt;block&gt; ]
*
* @return true If an &lt;if statement&gt; is recognized.
*/

Here is one way of writing the code for
        <if statement> ::= "if" <condition> <block> [ "else" <block> ]

public boolean isIfStatement() {
if (keyword("if")) {
if (isCondition()) {
if (isBlock()) {
if (keyword("else")) {
if (isBlock()) return true;
else error("No block after 'else'.");
}
else return true;
}
else error("If statement does not control a block.");
}
else error("Invalid condition in an if statement.");
}
return false;
}

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() {
if (!keyword("if")) return false;
if (!isCondition()) error("Invalid condition in an if statement.");
if (!isBlock()) error("If statement does not control a block.");
if (!keyword("else")) return true;
if (!isBlock()) error("No block after 'else'.");
return true;
}

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() {
if (!keyword("if")) {
return false;
}
if (!isCondition()) {
error("Invalid condition in an if statement.");
}
if (!isBlock()) {
error("If statement does not control a block.");
}
if (!keyword("else")) {
return true;
}
if (!isBlock()) {
error("No block after 'else'.");
}
return true;
}

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.