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.
CodeBlocks is a cross-platform C++ IDE (Integrated Development Environment) that allows developers to code, debug, build, run and deploy projects. It provides powerful options to customize your development environments, such as source control integration and graphical views of memory and CPU usage.
Overview. A code block, sometimes referred to as a compound statement, is a lexical structure of source code which is grouped together. Blocks consist of one or more declarations and statements.
html example. This contains two functions called a() and b() , and three variables — x , y , and z — two of which are defined inside the functions, and one in the global scope. It also contains a third function called output() , which takes a single parameter and outputs it in a paragraph on the page.
If your function does multiple things that are lengthy enough that you would consider splitting those things into blocks like this, then you should probably split the function into multiple, smaller functions.
There are, of course, scenarios in which introducing a new scope block is useful. For example, if you use a scoped_lock
of some kind to lock a mutex or other synchronization object, you can ensure that you only hold the lock for as short a time as necessary by introducing a scope block.
Implementation Patterns by Kent Beck has a very good chapter on this topic. Splitting into blocks will help in refactoring into separate functions.
For example something like this
void process() {
//code for input
//code for increments /tally
//code to populate objects and output
}
will become
void process() {
input();
tally();
output();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With