If I have a method that does multiple, related things, is it good practice to stick each “thing” that the method does into a seperate block?
Ex.
{
int var
//Code
}
{
int var
//More Code
}
It would help reduce the number of local variables, and make the code more readable, but I’m not sure if it’s a good idea.
Well, it’s certainly good practice to restrict the scope of variables as much as possible. They’re less likely to be re-used unnecessarily, and you’re more likely to define them when you declare them, which avoids bugs due to undefined variables and such. There are also plenty of cases where you have an object which does something while it’s constructed and when it’s destroyed, and you want to scope that (for instance, the hour glass in MFC is displayed while its object exists and disappears when it’s destroyed in MFC; objects for locking and unlocking mutexes are another good example), and in such cases, scoping the variables with braces makes good sense. So, there are plenty of cases where it makes good sense to create blocks of code specifically to scope variables.
However, there are some problems with doing this heavily.
It can become hard to read if you have a lot of code blocks within a function.
If you try too hard to scope variables as tightly as possible, you run into issues with having to declare variables which need larger scoping earlier than you would otherwise and aren’t always able to define them when declaring them.
Functions often express what you’re trying to do far better.
So, using extra braces to scope variables can be good practice (reducing the scope of variables as much as reasonably possible certainly is), but in many cases, it’s far better to break up your code into multiple functions. Code can be far easier to understand when you have named functions than arbitrary blocks of code. So, if you’re in a position where you’re looking to declare very many separate blocks of code within a function, consider breaking it up into multiple functions – this is especially true if each of those blocks is directly within the function rather than nested further. So, cases of
would likely be better broken into multiple functions than separate blocks.
There are certainly times when separate blocks can be good and useful, but generally separate functions would be better.