Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to separate code into blocks?

Tags:

c++

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.

like image 429
LM. Avatar asked May 18 '10 23:05

LM.


People also ask

Why do we use code blocks?

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.

What are code blocks in programming?

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.

Can html have functions?

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.


2 Answers

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.

like image 186
James McNellis Avatar answered Nov 15 '22 08:11

James McNellis


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();
}
like image 36
Srikar Doddi Avatar answered Nov 15 '22 06:11

Srikar Doddi