Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Would you ever use curly braces for making your code more organized and readable? for instance I could have:

- (void)methodName {
    ...
    // action 1
    {
        ...
    }
    ...
}

Where I'm using the curly braces to organize few statements that perform a certain task. My goal is also to make the code more readable. Is this a proper way of helping with code organization or should I rather organize using methods or?

share|improve this question
1  
I do this sometimes to keep variables as local as possible. It can also help to reuse the same variable name in one function. –  dialer May 10 '13 at 18:52
    
@dialer if the issue is code readability and organization rather than scoping would you still use this or there are better methods? –  x89a2s May 10 '13 at 18:56
2  
I would argue that functions are for organization; and meaningful comments and variable names, as well as empty lines are for readability. Having variables scoped locally may contribute to this (the reader knows that he only needs to care about the variable inside its scope). If I saw curly braces for no apparent reason, I'd probably be confused. –  dialer May 10 '13 at 19:01
add comment

1 Answer

up vote 3 down vote accepted

In general, I'd say that if a function grows to the extent that it needs the device suggested to make it clear, it is perhaps necessary to re-design the function.

Having said that, I have seen this done in the context of mutex locking and interrupt blocking, such as:

lock(mutex); {
    do_stuff();
    with_mutex_locked();
} unlock(mutex);

The intention is to make the 1-1 correspondence between locking and unlocking clear and to highlight the bracketed code. This clearly becomes less tidy if there is a need to break out of the block, but otherwise although I don't really like it I cannot give a convincing reason why not. It is just unconventional.

Is it really any clearer than:

lock(mutex);
do_stuff();
with_mutex_locked();
unlock(mutex);

with blank lines at each end?

share|improve this answer
    
@dialer and William, Thanks for your responses. I will stop using curly braces for the purposes I mentioned and agreed with your comments. –  x89a2s May 10 '13 at 23:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.