pcb-rnd knowledge pool

 

Programming tips: bail-out

prog_tip1 by Tibor 'Igor2' Palinkas on 2018-01-27

Tags: dev, tips, programming, style, readable, simple, code

node source

 

 

Abstract: Code organization tips and tricks to get the code simpler and more readable: bail-out.

 

Very often the code needs to check a lot of things to make sure the final operation it needs to perform will not fail. First the classic, positive construction of these conditions, then the bail-out version:


/* classic */
function do_something()
{
	prepare1;
	if (valid1) {
		prepare2;
		if (valid2) {
			prepare3;
			if (valid3)
				doit;
			else
				error3;
		}
		else
			error 2;
	}
	else error1;
}



/* bail out */
function do_something()
{
	prepare1;
	if (!valid1) {
		error1;
		return;
	}

	prepare2;
	if (!valid2) {
		error2;
		return;
	}

	prepare3;
	if (!valid3) {
		error3;
		return;
	}

	doit;
}

Pros for the bail-out structure:


function layer_checks()
{
	prepare2;
	if (!valid2) {
		error2;
		return bad;
	}

	prepare3;
	if (!valid3) {
		error3;
		return bad;
	}
	return good;
}

function do_something()
{
	prepare1;
	if (!valid1) {
		error1;
		return;
	}

	if (!layer_checks())
		return;

	doit;
}