[R] Coding style query (braces)

Marc Schwartz MSchwartz at mn.rr.com
Wed Oct 25 23:14:39 CEST 2006


On Wed, 2006-10-25 at 16:44 -0400, Mike Prager wrote:
> Re:  placement of braces and "else" clauses.  At the R prompt, I
> believe their placement must avoid causing a syntactically
> complete statement at the wrong place.  This can results in what
> might be considered rather awkward looking code.
> 
> IF it is known that code will be used via sourcing a script
> only, is there any potential problem with placing braces as
> shown below ?
> 
> xxx <- function()
> {
> 	blah()
> 	if (x > 3)
> 		{ 
> 		... if statements here ...
> 		}
> 	else
> 		{
> 		... else statements here ...
> 		}
> 
> }	# end function
> 
> 
> This is code that I would like to work not just now, but in
> years to come.
> 
> Comments appreciated.


Mike,

This is actually covered in the Details section of ?"if":

"Note that it is a common mistake to forget to put braces ({ .. })
around your statements, e.g., after if(..) or for(....). In particular,
you should not have a newline between } and else to avoid a syntax error
in entering a if ... else construct at the keyboard or via source. For
that reason, one (somewhat extreme) attitude of defensive programming is
to always use braces, e.g., for if clauses."

Thus:

xxx <- function()
{
   blah()
   if (x > 3)
   { 
      ... if statements here ...
   } else {
    ... else statements here ...
   }
}       # end function



Note that some will use a slightly different opening brace of:

if (x > 3) { 
  ... if statements here ...
...


That tends to be a coding style issue and may be biased by prior coding
experience in other languages.

HTH,

Marc Schwartz



More information about the R-help mailing list