A question of layout. First, a couple of case studies.
Casey's code is usually layed out something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 | BOOL myFunc()
{
BOOL returnValue = YES;
if(something1)
{
if(something2 && !something3)
{
for(int x=0; x<something4; ++x)
{
if(something5)
{
returnValue = NO;
break;
}
}
}
else
{
returnValue = NO;
}
}
return returnValue;
}
|
There are two features I'm interested in here: firstly, it only exits at the
end of the function, and secondly, there are many levels of nesting.
My code would have multiple exit points but have as few levels of nesting as what -- to me at least -- makes the code most readable:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 | BOOL myFunc()
{
if(!something1)
return NO;
if(!something2) *
return NO;
if(something3) *
return NO;
for(int x=0; x<something4; ++x)
{
if(!something5)
continue;
return NO;
}
return YES;
}
* if something2 and something3 are logically related then I would combine them as (!something2 || something3)
|
You also need to picture these functions filled out with all the in-between code, which alters the trade-offs somewhat: in Casey's version the closing braces are often off screen, and in my version the multiple exit points (whether returns, continues, or breaks) can get lost in the code jungle.
--
Casey's approach doesn't slow Casey down at all. But I wondered how everyone else approached the tradeoff, and whether there are any mines lurking in the deep waters of either layout?