3

Is it a good style to place curly brackets around logical parts of sequential code to structure it?

An advantage would be, that you can collapse these blocks in an editor like vim and get a better overview of your code.

I talk about code, which does not belong in a separate function, due to parameter passing overhead, or to many one-time-only called functions or simmilar.

Example:

struct abc {
  int a = 1;
  string b = "foo";
  char c = 'c';
  //...
} 

//...
abc myabc;
//assigning variables
{
   myabc.a = 111;
   myabc.c = 'x';
   //...
}

can be collapsed to (vim):

//...
abc myabc;
//assigning variables
{...}

I know about initializer lists, and the example is of course made up. Other examples would be some printing, or a big gnu longopts block at the beginning of the main method or looking for some values in a std::map cache-variable.

Jounathaen
  • 143
  • 1
  • 5
  • 1
    Possible duplicate of [How would you know if you've written readable and easily maintainable code?](https://softwareengineering.stackexchange.com/questions/141005/how-would-you-know-if-youve-written-readable-and-easily-maintainable-code) – gnat Sep 15 '17 at 09:54
  • There is nothing wrong with functions that are called only one time. – Karl Bielefeldt Sep 15 '17 at 10:40
  • 3
    @gnat I don't think it is a duplicate of that question – Jounathaen Sep 15 '17 at 11:34
  • Styling code to take advantage of various editor features would seem to be a questionable enterprise IMHO. – Robbie Dee Sep 15 '17 at 14:59

1 Answers1

11

The only reason to use a block/compound statement aside from control flow constructs like if/else/while is if you need a nested scope, e.g. to limit the lifetime of a local variable. The block specifies when the destructors will run which may be very important. E.g. you might use a class that acquires a lock via RAII, and you want to release it as soon as possible. Then:

some_code();
{
  Lock acquire_some_resource{};
  do_stuff_while_lock_aquired();
}  // destructor releases lock
continue_without_lock();

Code blocks are not a suitable mechanism for structuring code because they will always (misleadingly) suggest they are used because of variable visibility or lifetime.

Instead:

  • use empty lines between unrelated statements to add visual rhythm to your code.
  • extract details into a separate function if it distracts from the main purpose. Pass arguments by reference if you are concerned about “parameter passing overhead”. You can also make sure the separate function has internal linkage, e.g. by declaring it in an anonymous namespace.
amon
  • 132,749
  • 27
  • 279
  • 375
  • I would argue that: con argument presented has lesser practical value than pro stated in the question. i.e. code_readability_difference = convenient block collapsing - "(misleadingly) suggest they are used because of variable visibility or lifetime " > 0 But, it's just my taste :). – hardyVeles Mar 22 '20 at 04:33