free hit counter

Thursday, March 30, 2006

inline constants to improve readability

Everyone talks about using constants in your code to improve readability, but sometimes I think it can obscure readability when a single use constant is stuck away in some header file with 100 other of them, and I'm more tempted to use a magic number ("aw, just this one time...") if I have to go fish around and open the file that has all the constants.

I think constants should follow the same rules as variables: use the least expansive scope possible, and declare as close to first usage as possible. I can't recall see this documented formally in any books, but I'm a firm beleiver. Here's an example:


const int top_row= 0;
const int span_to_bottom_row= -1;
const int second_column= 1;
const int no_col_span_for_thermo= 1;
loMainGrid->addWidget(thermo, top_row, second_column, span_to_bottom_row, no_col_span_for_thermo);

const int second_row= 1;
const int first_col= 0;
loMainGrid->addWidget(compass, second_row, first_col);

This makes it much easier to see the difference between the less used overload for spanning grid cells and the more standard single cell, two argument form.

loMainGrid->addWidget(thermo, 0,1,-1,);
loMainGrid->addWidget(compass, 2,1);

So, did you catch the semantic error in the no constants example? If you're being more explicit it's easier to remember that the second row is actually index 1, and the first column is index 1.

Also notice the usage of non caps for constants. I still beleive MAGIC_NUMBER_USED_ALL_OVER should be capitalized, but heavy usage of these throwaway constants can REALY MAKE IT LOOK LIKE YOUR CODE IS SHOUTING.

0 Comments:

Post a Comment

<< Home