Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Code design 2

Status
Not open for further replies.

mattias1975

Programmer
Jul 26, 2004
36
0
0
SE
I have some questions.

Which of these two is the best design?

Ex 1.

int main()
{
int a = function1();
function2(a);
}

function1(){
int a;
.......
return a;
}

Ex 2.

int main()
{
function1();
}

function1(){
int a;
function2(a);
}

Are there any designpaterns or any standard designrules for non objectoriented language like c?
 
Write whatever suits you, the logical design, and the people who will maintain your code.

Personally, I would avoid doing this:
int a = function1();
Splitting it to two lines: declaration, then assignment; would be more my prefered style.

As for imbedding the call to function2 within function1, that really is going to depend on what the code is actually doing. For example, you may want to call function1 multiple times throught your program, without calling function2. How are you going to do that if they're imbedded? On the other hand, function2 might be required to be called for EVERY call to function1, in which case the embedded option is just fine.

Choices.. choices... ;-)
 
Are you asking what should go in main?

Typically, command line argument parsing and top-level program logic goes into main.

There's no need to create another function whose only purpose is to be called by main.


Are you asking about how functions should work?

Depends on what process or mechanism function1 is an abstraction for.

If function2 performs part of that process or mechanism, then it should be called from function1 ans in Ex. 2.

If function2 represents a separate process or mechanism from function1, and should be called upon the result of function1 after function1 has already "happened," then you'd call them one after the other as in Ex. 1.

Basically, just read the names of the functions and decide what they're claiming to do, then do whatever is sufficient to get them to do it and no more.


In other words, you'll use both "styles," because both are appropriate for different things.
 
He's asking where the call to function2 should go.. In general that is dependant on when you need the return of function. I try to keep most I/O as close to main as possible, and I try to keep the stack as small as possible, so I'd typically use Ex1 if the two are truely logically equivelent (note the only to make a function is to avoid writing the same code over and over - so I'd also check to see if everytime I for function1 I call function2 (with same parameters) after, if that is the case function2 goes in function1.

just my 2.0 * 10 ^ -2
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top