Coding style and undoing indentation hell
virtualdub.org
virtualdub.org
// Original
function render() {
$return = null;
if($condition1) {
if($condition2) {
$return = 2;
} else {
$return = 1;
}
} elseif($condition3) {
$return = 3;
} else {
$return = 4;
}
return $return;
}
But I'd rather read: // Refactored
function render() {
if($condition1 && $condition2) return 2;
if($condition1) return 1;
if($condition3) return 3;
return = 4;
} function render() {
$return = null;
if($condition1 && $condition2) $return = 2;
elseif($condition1) $return = 1;
elseif($condition3) $return = 3;
else $return = 4;
return $return
} r = 0;
outer: {
foreach (x in a) {
foreach (y in b) {
if (condition(a, b)) {
r = 1;
break outer;
}
}
}
return r;
instead of foreach (x in a) {
foreach (y in b) {
if (condition(a, b)) {
return 1;
}
}
}
return 0;See http://anthonysteele.co.uk/the-single-exit-point-law and http://anthonysteele.co.uk/returning-to-multiple-exit-points
ETA: I'm amused by how easily the LISP philosophy applies here: any problem can be solved with enough lambdas.
Then your choices include a try...finally block, a "using" statement if you're in c#, or ... limiting yourself to only 1 return. Multiple returns don't fix the problems in all cases, just most of them.
I'm assuming that this is on a language that has automatic garbage collection. The 1-return rule came about in C, which does not and so has a lot more cases where manual clean-up is required.
I hate this style (from the article):
if (...) {
if (...) {
...
} else {
if (...) {
...
} else if (...) {
...
} else {
...
}
}
and prefer this: if (...)
{
if (...)
{
...
}
else
{
if (...)
{
...
}
else if (...)
{
..
}
else
{
...
}
}
}
The first example is confusing and hard to read. The second is clean and easy to read.As to the question of optimization, that's a different matter. Lots of tricks can be used to compress code into fewer statements on a case by case basis:
if(pushbutton == 0)
{
led = 12;
}
else
{
led = 24;
}
can become led = (pushbutton == 0) ? 12 : 24;
or led = (pushbutton * 12) + 12;
or led = 12 * (pushbutton + 1);
etc.I have worked with people that were dogmatic that one form was objectively better than another form, rather than it being a matter of local optimization in the brain; I have difficult working with these people because they tend to show similar rigidity and confusion of the subjective with the objective in other areas, and such small mindedness limits what type of engineering solutions one is able to come up with.
Hard to see. That's my point. And that's why I tend to favor the second style.
I'll use any convention if required, but if given a choice I go for styles that protect me from my own dumb mistakes as much as possible.
I strongly avoid however converting logical semantics into arithmetic ones. The LED example where:
led = (pushbutton * 12) + 12;
Makes me cringe.You know that the person who wrote that assumed 'non-zero' meant it was pressed, not '1' means its pressed at some point the pushbutton is connected to bit 3 of the I/O port and the the kid was doing a byte read 'cuz it was easy' and now the value of pushbutton is 8 (which still would work on their code but not the refactored code) and led gets the value 108 and the code that takes the LED value turns on some random GPIO bit somewhere else because it can "only" get either 12 or 24 when now it can get a lot of different values. And a long escalation in manufacturing that the 'new software screws up the gizmo' turns out to be a side effect from refactoring. Been there, done that, wrote the after action report. No thanks!
First I understood that you were not seriously proposing this sort of I/O code, but as someone who has been around the block my share of times I know that such code both exists and is in production, almost exactly as written. The memories are like a war veteran who can't forget the trenches, I wince now and then :-).
Second, my comment was that code which has a 'boolean' flow is probably boolean code, and not arithmetic code. So any refactoring that 'assumes' boolean and uses arithmetic becomes a landmine for some future coder to trip over. MUCH better to refactor the code as such into:
led = (button)? 12 : 24;
Than "assuming" that true is '1' and false is '0'. When reading old code I've trained my self to read the statement if (variable == 0) {
// this code assumes the variable is zero
} else {
// this code has to work for all non-zero values
}
Which may not have been the programmer's intent, but it is what they wrote.It's been a long, long time since I've checked button activity that way. These days andy time I do embedded work I tend to use either my own RTOS or a third party RTOS. In most of these cases UI events get turned in to messages in a message loop (sort of like programming for Windows). So it is likely that there's a big switch statement somewhere picking picking off messages off the FIFO and processing them accordingly. The low-level stuff happened somewhere else. The message would indicate the event that took place (UP, DOWN, CLICK, DOUBLE_CLICK) and parameters in the message packet would identify the button or buttons (in the case chords are enabled) that generated the event.
Fun stuff. Wrote this code years ago and keep reusing it. It simply works. Now doing a lot more iOS and web development. iOS can feel a lot like embedded development at times.
if
if
else
if
else if
else
In other words, I prefer CoffeeScript.Good procedural code is factored into short functions, which would make some of the types of programs the article is alluding to easier to read.
Also, object oriented programming can be a good option for reducing cyclomatic complexity in a lot of different situations where the system you are modeling lends itself to a class structure. And CoffeeScript makes this easier also.
led = (pushbutton == 0) ? 12 : 24;
or led = (pushbutton * 12) + 12;
or led = 12 * (pushbutton + 1);
"""It might be worth pointing out that the latter two don't actually have the same result as the if/else.
That said, "pushbutton" could very well be limited to the values 0 and 1 during the keypad scanning, debouncing and decoding code.
Chill bro.
I've programmed in everything from entering hex code into a hexadecimal keypad to assembly, Forth, APL and beyond. Sure, languages can influence style. I wouldn't go as far as calling any language "ugly". There's that initial phase of exposure when one might not be comfortable with the language constructs. And yes, at that moment in time it is natural to feel that a language might be "ugly". I certainly felt that way when learning Objective-C. Once you get on the other side and you start using the language for real work things can change. I don't hate any particular language but do enjoy some more than others. Forth, APL and Lisp were a lot of fun to work with.
Case in point - Linux networking code, and more specifically sockets handling part. Mr. Kuznetsov did an excellent job abstracting a lot of things behind interfaces (= blocks of function pointers), but at the same time this made it much much harder to follow the code. It's basically impossible to trace the code by hand without a pen and paper.
(edit) To elaborate on the context - reading and tracing the code straight off the source files is a necessity of kernel development, routinely required for both debugging and writing new code.
It's not going to do all of the work for you, but it'll reduce some of the cognitive load.
if (!test()) {
handle_failure();
} else {
// do lots of work
}
is just another incarnation of if (NULL == v)
i.e. it sacrifices a natural flow of code and makes it harder to follow for something of a superficial value.Also this -
if (!test1()) {
handle_failure_1();
return false;
}
is fine unless the function needs to do a cleanup, which is pretty much always the case, and which in turn means that the { } block with grow with every if and it will include a lot of redundant code.A far cleaner and easier to follow approach is to use if-goto, whereby all cleanup code sits at the bottom of the function (where it naturally belongs) and the flow jumps to the appropriate part of the cleanup on failure. The only exception is when there's no cleanup needed, in which case it can do if-return.
Should these be assert()s? ;)
Practically speaking, your function should not be failing because your other code passed it invalid parameters. That's a bug in the former. That's why parameter validity should be asserted.
Sure, various of the refactorings given are sensible. But the basic problem is not indentation. If something can be simplified, simplify it. If something is too long, break it into pieces. But if something is tree-structured, that is what it is, and it probably ought not be bent out of shape.
(Note: Fowler's refactoring 'Replace Nested Conditional with Guard Clauses' is very specific -- it does not declare that all nesting is bad.)
A tree-like-indentation structure is a perfectly good element of programming -- why try/want to change it into something else?
In fact, a good case could be made that software in its most fundamental essential conception is tree-structured -- even that engineering generally is tree-structured.
I try to limit my conditionals to inline statements:
$x = $y if $b;
Often joined with early returns: return $b if $a;
If I find myself coding an if/else branch, that's often a clue that I should refactor this chunk into a function that can use early returns to avoid nested conditionals:so
if ($a == FOO) {
$c = $d;
}
else if ($a == BAR) {
$c = $e;
}
else {
$c = $f;
}
becomes $c = get_val($a);
...
sub get_val {
my ($a) = @_;
return $d if $a == FOO;
return $e if $a == BAR;
return $f;
}
Thankfully much of my coding lately is in perl, which lets me use postfix "if/unless" as well as "and/or" to avoid having to use braced conditionals.I also love myself the ternary operator. Basically my take comes down to "use conditionals for one-line assignments only, NOT for block execution".
if (bad1) fail();
if (bad2) fail();
if (bad3) fail();
step1();
step2();
step3();
step4();
return SUCCESS;
To me, this is a very nice way to structure things when you can. You get a checklist of things that might be wrong, and then comes the wonderfully naive straightforward implementation.one easy trick is to structure your code such that 'null' is impossible, by initializing to an empty value, or re-ordering the way things happen, or using exceptions or error-monad.
But, kudos: I can send this to my team instead of having to write it myself. Win!
BOOL do_stuff_with_resources()
{
int success = FALSE;
char *memBuf = (char *) malloc(256 * 1024);
if (NULL == memBuf) goto cleanup;
if (randBomb()) goto cleanup;
FILE *fp = fopen("dummy-file.txt", "w");
if (NULL == fp) goto cleanup;
if (randBomb()) goto cleanup;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sock) goto cleanup;
if (randBomb()) goto cleanup;
int shmId = shmget(0x1234ABCD, 256*1024, IPC_CREAT);
if (-1 == shmId) goto cleanup;
shmRegion = (char *) shmat(shmId, NULL, 0);
if ((char *) -1 == shmRegion) goto cleanup;
if (randBomb()) goto cleanup;
sem_t st = -1;
if (-1 == sem_init(&st, 0, 1)) goto cleanup;
if (randBomb()) goto cleanup;
// TODO: Do stuff
success = TRUE;
cleanup:
if(-1 != st)
{
sem_destroy(&st);
}
if(-1 != shmId)
{
shmctl(shmId, IPC_RMID, NULL);
}
if(-1 != sock)
{
close(sock);
}
if(NULL != fp)
{
fclose(fp);
}
if(NULL != memBuf)
{
free(memBuf);
}
return success;
}I'm going to work with a couple of assumptions:
1) The test casts which he refactors to test*() methods are non-trivial 2) The handlers _may_ be large sets of code
Here's a way to handle one of this refactored methods:
if (!test1()) { handle_failure_1(); return false; }
if (!test2()) { handle_failure_2(); return false; }
if (!test3()) { handle_failure_3(); return false; }
handle_success(); return true;
That's a lot of potential code we're dealing with in this class.
What if:
class HandlesFailure1
def handles_this_case(params)
#code from test1()
end
def handle(params)
#code from handle_failure_1()
return false;
end
endclass HandlesFailure2
def handles_this_case(params)
#code from test2()
end
def handle(params)
#code from handle_failure_2()
return false;
end
endclass HandlesFailure3
def handles_this_case(params)
#code from test3()
end
def handle(params)
#code from handle_failure_3()
return false;
end
endclass HandlesSuccess
def handles_this_case(params)
return true
end
def handles(params)
//code from handle_success
return true
end
end#And now the original class
class DoesSomething
#There are ways to set this up fairly easily. One simple way it to just new it up here, but you could auto-wire it too
handlers = [HandlesFailure1, HandlesFailure2, HandlesFailure3, HandlesSuccess]
def do_something(params)
handlers.each do |handler|
return handler.handle(params) if handler.handles_this_case(params)
end
end
endThere. Now there's a loop and an if. Check each case and either handle or toss it out. This can also work for the case where you might want multiple handlers to handle something, just don't return on the first one.
I'm not saying it's the right way, but it's another way.
Pros: It really helps to group together the handling methods with the test methods. Very simple dispatch method
Cons: Separate classes, and harder to view all the handlers together.
Generally these days I prefer functional decomposition for that (actually honestly I'm preferring C++ RAII style where you get the cleanup for free in almost all cases). That is, do something which requires cleanup (e.g. allocate memory, take a mutex, etc...), call a function to "initialize" the thing you just did, check results and free it on failure. So the allocation and cleanup happen next to each other in the code. Nest as needed for complicated resource strategies, and it scales well. No one is ever confused about what the state is supposed to be.
RAII is the best part about C++!
In this case, it makes the control flow more readable.
The gotos can be replaced with stuff like this:
foo, err := bar()
if err != nil {
return err
}
defer foo.cleanup() // or what have you
Now, right before the function returns, Go will call `foo.cleanup()` and your `cleanup()` call sits right next to the initialization code. It's a lot easier to tell whether or not you are (or someone else is) doing cleanup properly.