Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A matter of coding style: Assignment statement in loop expressions.

 
Marcus Jastrebowski
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Best Wishes,
Marcus
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Marcus Jastrebowski:
Or perhaps the intention of these examples in the book is to show how SCJP obfuscates the code readability?


Hi Marcus,

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic