Skip to content
Advertisement

Is it bad practice to separate sections of code inside one method with curly brackets? [closed]

I tend put multiple lines of code that fullfill a certain task into blocks, with a small comment on top, like this:

public void doSomething(){
    // common variables needed by all blocks

    { // comment for block 1
        ...
        ... about 5 to 30 lines of code
        ...
    }

    { // comment for block 2
        ...
        ... about 5 to 30 lines of code
        ...
    }

}

I do this because in my opinion, it’s easy to read, variables needed by one block won’t be able to do harm in another block and because I don’t want to make separate methods for block that won’t be needed somewhere else.

Would you say this is bad practice? A lot of people I’ve coded with disagree with this style of coding. I know there are regions in c# but they do not isolate variables.

edit: because everyone is suggesting I make methods out of the blocks: Sometimes I do but I don’t want to if the class already has 20+ methods, the blocks are not needed by any other method and the method with all the blocks is still small enough .

Advertisement

Answer

I don’t think this is bad practice, and I do it too, but I would encourage you to break the method into smaller ones. Do you really need a >50 lines method?

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement