This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I have been slowly digging my way through the Chapter 6, in Sierra/Bates. And, in a couple of examples, I stumbled upon these type of constructs:
I'm wondering why don't we write this fragment simply like that:
It seems to me that the second fragment is stylistically more readable (and compact). Also, the variable 'b' is not used anywhere, so what is the assignment for? But then of course I've been wondering if my idea of code readability (and proper programming style) is rather shaky in this case? Or perhaps the intention of these examples in the book is to show how SCJP obfuscates the code readability?
Variable b is used to evaluate the while loop. which could have been avoided by the second example. Second example is better as it saves one addtional boolean variable creation and assignment fom hasNext to boolean.
Originally posted by Marcus Jastrebowski: Or perhaps the intention of these examples in the book is to show how SCJP obfuscates the code readability?
I'm pretty sure you hit the nail on the head there. The SCJP exam designers seem to love trying to trip people up by using = instead of == in conditions, so K&B puts a bunch of these constructs here and there to give you practice in looking out for this trick. As you noted, it's rarely (if ever) useful to actually use such expressions if you're not an evil exam writer.