Problem in code sample


#1

In the code sample in ch. 21, I see:

if (mPhoto != null)
            json.put(JSON_PHOTO, mPhoto.toJSON());
            json.put(JSON_SUSPECT, mSuspect);

This just can’t be right! IMHO it should be either:

if (mPhoto != null) {
            json.put(JSON_PHOTO, mPhoto.toJSON());
            json.put(JSON_SUSPECT, mSuspect);
}

or

if (mPhoto != null)
            json.put(JSON_PHOTO, mPhoto.toJSON());
if (mSuspect != null)
            json.put(JSON_SUSPECT, mSuspect);

FWIW I used the second one.


#2

Yes. This is where they saved critical page space (and countless trees) by not including the parenthesis and incorrectly formatted it in print. The last one is correct. They need their own IF statements.


#3

Yep - this was a copyediting error in the indentation, introduced because we elected not to include braces on our if statements.

Learn from our mistakes: don’t let your if statements leave the house without their braces.


#4

But if json.put(JSON_SUSPECT, mSuspect) is supposed to be contained in the if statement, what is the reason for only putting the suspect if a photo exists? Or were you saying it should NOT be contained in the if statement?


#5

I think he meant they should both have their own if statement.

I prefer keeping my single line ifs on a single line, like so (but that may be an artifact of other programming languages I’ve used over the years):

	if (mPhoto != null) json.put(JSON_PHOTO, mPhoto.toJSON());
	if (mSuspect != null) json.put(JSON_SUSPECT, mSuspect);

#6

I am not a fan of indentation as program structure. Braces are your friend. But sometimes they are fine to do away with (like when done on one line).

I often put the if clause and statement on one line if the statement is short and sweet.

if (blah) do stuff;

If there is an else to it and it’s statement is also short, then I try to keep it all on one line with a tertiary statement ( ? : ).

value = (blah) ? firstOption : secondOption;

If not on one line, braces. Always braces. I try to never rely on indentation for program flow when it can be avoided.

if (blah)
{
     do stuff;
}
else
{
      do other stuff;
      and more stuff;
}