[RFC] CodingStyle

Denis Vlasenko vda at ilport.com.ua
Thu Feb 23 10:39:55 UTC 2006


Hi folks,

I think we need busybox preferred coding style to be writeen down.
It's not meant to _force_ developers to absolutely always follow it
(currently most of busybox does not follow it), but at least
people will know what style we like most.

Draft is below (jf course it's shamelessly stolen from Linux kernel...)
--
vda

======================================================================
		Busybox coding style

This is a short document describing the preferred coding style for the
busybox.  Coding style is very personal, and we won't _force_ our
views on anybody, but this is what goes for anything that we have to be
able to maintain, and we'd prefer it for most other things too.  Please
at least consider the points made here.

	 	Indentation

Tabs are 8 characters, and thus indentations are also 8 characters.
There are heretic movements that try to make indentations 4 (or even 2!)
characters deep, and that is akin to trying to define the value of PI to
be 3.

Rationale: The whole idea behind indentation is to clearly define where
a block of control starts and ends.  Especially when you've been looking
at your screen for 20 straight hours, you'll find it a lot easier to see
how the indentation works if you have large indentations.

Now, some people will claim that having 8-character indentations makes
the code move too far to the right, and makes it hard to read on a
80-character terminal screen.  The answer to that is that if you need
more than 3 levels of indentation, you're screwed anyway, and should fix
your program.

In short, 8-char indents make things easier to read, and have the added
benefit of warning you when you're nesting your functions too deep.
Heed that warning.

Get a decent editor and don't leave whitespace at the end of lines.


		Breaking long lines and strings

Coding style is all about readability and maintainability using commonly
available tools.

The limit on the length of lines is 80 columns and this is a hard limit.

Statements longer than 80 columns will be broken into sensible chunks.
Descendants are always substantially shorter than the parent and are placed
substantially to the right. The same applies to function headers with a long
argument list. Long strings are as well broken into shorter strings.

void fun(int a, int b, int c)
{
	if (condition)
		printk(KERN_WARNING "Warning this is a long printk with "
						"3 parameters a: %u b: %u "
						"c: %u \n", a, b, c);
	else
		next_statement;
}

		Placing Braces

The other issue that always comes up in C styling is the placement of
braces.  Unlike the indent size, there are few technical reasons to
choose one placement strategy over the other, but the preferred way, as
shown to us by the prophets Kernighan and Ritchie, is to put the opening
brace last on the line, and put the closing brace first, thusly:

	if (x is true) {
		we do y
	}

However, there is one special case, namely functions: they have the
opening brace at the beginning of the next line, thus:

	int function(int x)
	{
		body of function
	}

Heretic people all over the world have claimed that this inconsistency
is ...  well ...  inconsistent, but all right-thinking people know that
(a) K&R are _right_ and (b) K&R are right.  Besides, functions are
special anyway (you can't nest them in C).

Note that the closing brace is empty on a line of its own, _except_ in
the cases where it is followed by a continuation of the same statement,
ie a "while" in a do-statement or an "else" in an if-statement, like
this:

	do {
		body of do-loop
	} while (condition);

and

	if (x == y) {
		..
	} else if (x > y) {
		...
	} else {
		....
	}

Rationale: K&R.

Also, note that this brace-placement also minimizes the number of empty
(or almost empty) lines, without any loss of readability.  Thus, as the
supply of new-lines on your screen is not a renewable resource (think
25-line terminal screens here), you have more empty lines to put
comments on.


		Naming

C is a Spartan language, and so should your naming be.  Unlike Modula-2
and Pascal programmers, C programmers do not use cute names like
ThisVariableIsATemporaryCounter.  A C programmer would call that
variable "tmp", which is much easier to write, and not the least more
difficult to understand.

HOWEVER, while mixed-case names are frowned upon, descriptive names for
global variables are a must.  To call a global function "foo" is a
shooting offense.

GLOBAL variables (to be used only if you _really_ need them) need to
have descriptive names, as do global functions.  If you have a function
that counts the number of active users, you should call that
"count_active_users()" or similar, you should _not_ call it "cntusr()".

Encoding the type of a function into the name (so-called Hungarian
notation) is brain damaged - the compiler knows the types anyway and can
check those, and it only confuses the programmer.  No wonder MicroSoft
makes buggy programs.

LOCAL variable names should be short, and to the point.  If you have
some random integer loop counter, it should probably be called "i".
Calling it "loop_counter" is non-productive, if there is no chance of it
being mis-understood.  Similarly, "tmp" can be just about any type of
variable that is used to hold a temporary value.

If you are afraid to mix up your local variable names, you have another
problem, which is called the function-growth-hormone-imbalance syndrome.
See next chapter.


		Functions

Functions should be short and sweet, and do just one thing.  They should
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,
as we all know), and do one thing and do that well.

The maximum length of a function is inversely proportional to the
complexity and indentation level of that function.  So, if you have a
conceptually simple function that is just one long (but simple)
case-statement, where you have to do lots of small things for a lot of
different cases, it's OK to have a longer function.

However, if you have a complex function, and you suspect that a
less-than-gifted first-year high-school student might not even
understand what the function is all about, you should adhere to the
maximum limits all the more closely.  Use helper functions with
descriptive names (you can ask the compiler to in-line them if you think
it's performance-critical, and it will probably do a better job of it
than you would have done).

Another measure of the function is the number of local variables.  They
shouldn't exceed 5-10, or you're doing something wrong.  Re-think the
function, and split it into smaller pieces.  A human brain can
generally easily keep track of about 7 different things, anything more
and it gets confused.  You know you're brilliant, but maybe you'd like
to understand what you did 2 weeks from now.


		Macros, Enums, Inline functions

Names of macros defining constants and labels in enums are capitalized.

#define CONSTANT 0x12345

Enums are preferred when defining several related constants.

CAPITALIZED macro names are appreciated but macros resembling functions
may be named in lower case.

Generally, inline functions are preferable to macros resembling functions.

Macros with multiple statements should be enclosed in a do - while block:

#define macrofun(a, b, c) 			\
	do {					\
		if (a == 5)			\
			do_this(b, c);		\
	} while (0)

Things to avoid when using macros:

1) macros that affect control flow:

#define FOO(x)					\
	do {					\
		if (blah(x) < 0)		\
			return WE_BUGGERED;	\
	} while(0)

is a _very_ bad idea.  It looks like a function call but exits the "calling"
function; don't break the internal parsers of those who will read the code.

2) macros that depend on having a local variable with a magic name:

#define FOO(val) bar(index, val)

might look like a good thing, but it's confusing as hell when one reads the
code and it's prone to breakage from seemingly innocent changes.

3) macros with arguments that are used as l-values: FOO(x) = y; will
bite you if somebody e.g. turns FOO into an inline function.

4) forgetting about precedence: macros defining constants using expressions
must enclose the expression in parentheses. Beware of similar issues with
macros using parameters.

#define CONSTANT 0x4000
#define CONSTEXP (CONSTANT | 3)

The cpp manual deals with macros exhaustively.


		Less important stuff

Preferred:				To avoid:

v = expr;				v=expr;
v += expr;				v+=expr;
for (i = 0; i < 10; i++) ...		for (i=0;i<10;i++) ...
if (a == 17) ...			if (a==17) ...

int primes[] = { 2, 3, 5 };		int primes[] = { 2,3,5 };
char *files[] = {			char *files[] =
	"/etc/mtab",                    	{ "/etc/mtab",                    
	"/proc/mounts",                 	"/proc/mounts",                     
	NULL                               	NULL};
};

char *msg;				char* msg; char * msg2;
char *const msg;			char * const msg;

pointer = NULL;				pointer = 0;

if (!pointer) ...			if (pointer == NULL) ...

(int)long_var				(int) long_var

sizeof(type)				sizeof (type)
sizeof(var)				sizeof var

function_call(a, b, c)			function_call (a,b,c)
if (expr) ...				if(expr) ...
for (...) ...				for(...) ...
while (...) ...				while(...) ...
do {					do {
	...					...
} while (expr);				} while (expr);


		Single-statement if, for, etc

if (expr)		    and		if (expr) {
	do_something				do something
					}

Both forms are considered to be ok. While first one is shorter,
second one is easier to convert to multi-statement one if such need
will arise.

Do not bother yourself with cleanup patches which try to convert
the source tree exclusively to first or second form.



More information about the busybox mailing list