• Post Reply Bookmark Topic Watch Topic
  • New Topic

Style Preferences for Conditional Returns  RSS feed

 
Stevens Miller
Bartender
Posts: 1445
30
C++ Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a routine that returns a boolean. If any of a series of tests fails, the routine returns false, otherwise it returns true. For example, the routine might test for whether or not an integer is both odd and greater than 99, thus:



I like the above because it suggests that "true" is the condition that applies if the incoming parameter meets all the required criteria. But I've sometimes seen this style used:



I like this less because, among other things, if that last criterion is removed, the "else/return true" must be moved up into the immediately preceding test (or else leave some funny whitespace, depending on how you go about removing the departing "if" statement), but it does avoid suggesting that "return true" is hard-coded (that is, it reinforces that "true" is a conditional return value, not inevitable).

Anyone else have preferences here?
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally I'd go with the following:

or if more clarity is required

 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I meant to add that if the choice was just between the two you gave, I'd go with the first one.
 
Stevens Miller
Bartender
Posts: 1445
30
C++ Java Netbeans IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tony Docherty wrote:Personally I'd go with the following:


Dear God, man, I'm not programming APL!

Yes, for the purpose of applying the criteria in my example, I might do something like that too. My actual code's criteria are rather more complex than can rationally be put into one line, however. More abtractly, my situation would be expressed thus:



Glad you support my own preference, though. I suppose one could defend it on the basis that it allows for conditional processing when true will be returned:


Though nothing stops that additional processing from being in the same clause as the "return true" statement as well.

This is just one of those things I need to take to the 'net, as, being a solo coder, there's no one here to ask.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!