Possible Duplicate:
How many lines of code should a function/procedure/method have?
Out team has a project of not well structured ansi-c code. I would like to use some CC techniques to tidy up the code base.
As for C code, we have a lot of pointers and a lot of NULL-pointer pitfalls to catch. Therefore there are lot of fragments which look alike. It’s like
if (pointer == NULL)
{
function1();
function2();
}
all over the place. Then there are an awful lot of functions that will be called after each other in the same fashion only with a few variations, like
function1();
function2a();
function3();
and
function1();
function2b();
function3();
all over the place.
I would like to extract those blocks as a single function to reduce LOC and copy-pasting. But that will create not only a (somewhat) orthogonal layer but also a handfull of function doing more or less the same, except for some details. And even worse, it will create functions that do a lot of things at once.
So, what’s a good strategy? What’s more important, lean code on high level, lean functions on low level or lean architecture? Which principle trumps the other? Seperation of concern or DRY?
I would like to refactor that beast but don’t know where to start.
To exploid the example below and put same names in. Lets assume we have
morningBath();
drinkCoffee();
if (checkMail())
{
answerMail();
}
and put that into morningRoutine(). Now we have
drinkTea();
morningBath();
if (checkMail())
{
answerMail();
}
and call it sundayMorningRoutine(). But then there is duplicated code. Or expand morningRoutine(day) as
if (day == sunday){
drinkTea();
morningBath();
} else {
morningBath();
drinkCoffee();
}
if (checkMail())
{
answerMail();
}
or maybe
if (day == sunday){
drink(Tea);
morningBath();
} else {
morningBath();
drink(Coffee);
}
if (checkMail())
{
answerMail();
}
I wonder if that is good style.. maybe.. Thanks for that hint!
Regarding C code, it’s perfectly normal to frequently encounter
NULLpointer checks, especially when it comes to function arguments. Personally, I prefer to let the caller resolve the situation, as in:Public functions, i.e. functions that are part of the API, should always check for
NULLpointers. Functions that are designatedstaticmay IMO drop those checks. And finally, there’s alwaysassert(). Those checks can be suppressed by the compiler flag-NDEBUG. I useassert()instaticfunctions instead ofif-statements and in “public” functions for tests that reveal that the caller didn’t actually understand the API as a whole, e.g. in a linked list lib:As for your second concern, I can see three options:
1) leave everything as it is – after all, it’s working.
2) introduce new functions:
3) introduce new parametrized functions:
Personally, I prefer the latter approach, but that is really just a matter of style.