Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How can we avoid spaghetti code?

Posted on 2005-04-11
35
Medium Priority
?
760 Views
Last Modified: 2007-12-19
The question asks itself.

Paul
0
Comment
Question by:PaulCaswell
  • 8
  • 6
  • 6
  • +8
35 Comments
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13753821
See here for the trigger for this question. Thankyou Beryl for the original thought.

http://www.experts-exchange.com/Programming/Q_21383494.html#13752856

Paul
0
 
LVL 10

Accepted Solution

by:
fds_fatboy earned 80 total points
ID: 13753974
Don't use GOTO.
Design and code for maintainability.
Don't use GOTO.
Clever code is bad.
Don't use GOTO.
Simple code is good.
Don't use GOTO.
Oh yes, don't use GOTO.
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13754032

0. Dont break the flow (dont use GOTO!).

I wholeheartedly agree.

1. Only return from the end of your functions.

My thought. What do you think?

2. Clever code is bad.

Please define 'Clever' more accurately and I'll consider it.

3. Simple code is good.

See '2'.

Paul
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 25

Assisted Solution

by:InteractiveMind
InteractiveMind earned 80 total points
ID: 13754092
Rather than using the same statements over and over again, just create a method/function (declare as inline if using C/C++ and if the function/method is small). So, for example, rather than using this (in Java):

int x = 1;
int y = 3;
int gradient = y / x;

System.out.println( "Gradient = " + gradient );

int x = 4;
int y = 2;
int gradient = y / x;

System.out.println( "Gradient = " + gradient );

and so on...

You could use something like this:

private int gradient( int x, int y )
{
   return y / x;
}

private void output( String str )
{
   System.out.println( str );
}

...

output( "Gradient = " + gradient( 1, 3 ) );
output( "Gradient = " + gradient( 4, 2 ) );

...

When you're using a lot of these, it would drastically decrease amount of code, and make it neater, and easier to understand and read (especially for the sake of someone other than the developer).

Also, always use comments, but remember that "less is more"... so, simple declarations, keep it neat, keep it simple.

Don't ever create methods/functions that already exist (in an existing API)!! I see people declaring their own PI variable, and creating their own encryption classes, where totally unecessary: don't re-invent the wheel!

I'll see if I can think up much more..... :)

Regards;
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 13754118
Also:

  NEVER EVER USE "WYSIWYG"'s ("visual GUI creators")!! They really make a mess of everything!  lol
0
 
LVL 5

Expert Comment

by:beryl666
ID: 13754475
Paul:
Welcome and Thanks. i learn much from you also.

beryl
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 13754834
get a copy of

Code Complete (2nd Edition)
Steve McConnell
Microsoft Press
ISBN 0735619670

and READ it.

one of the best books ever written on the general principles of 'good' coding practice.

AW
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 13755309
Arthur,
I think that I will take you up on that recommendation  :)  Cheers!
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 13755344
Arthur,

you recommend the 2nd edition, but is it much better than the first, do you know? Because, I can get the 1st edition for only £3, whereas the second is £20..
Could you say that it's worth the extra cash?

Regards;
0
 
LVL 32

Assisted Solution

by:r-k
r-k earned 80 total points
ID: 13756317
I agree with most of what the others have already said. However, I am not sure that "avoid goto's" is a real answer. More important is to keep your code modular, i.e. each module/function should be small (as can be) and self-contained, and commented in a meaningful way (avoid superfluous comments). After that it won't matter whether a few goto's slip in (at least they won't have far to go to :))

Finally, whoever said that don't use Visual GUI creators (i.e. Wizards that generate code), I couldn't agree more.
0
 
LVL 1

Assisted Solution

by:wad4ever
wad4ever earned 80 total points
ID: 13757405
In the old days, we had "programming". Basically whatever you did was great. If it was fast, tight, and clever, no matter how hard to understand, your peers considered you to be smart.

Over time, computation power increased, and it was more important that code be maintainable by other programmers than the original author. Enter structured programming, which does a good job of eliminating spagetti code.

After structured programming, as programs got much larger, we got object oriented programming, with it's data hiding and abstraction. More recently, we have pattern-oriented design.

Spagetti code is still written by a few junior high-school students and amateurs programmers. And *sigh* sometimes by those who should know better.

What's funny is when people try to write object-oriented spagetti code... My what a mess!

--- Eric
0
 
LVL 44

Expert Comment

by:Arthur_Wood
ID: 13757516
IdleMind>>the fact that the second edition is current, and the first edition was written 'many'(read 10) years ago, should answer your question.  as the intor on www.bn.com states:

"For ten years, Steve McConnell’s Code Complete has inspired programmers to get better at their profession and has given them powerful insights for doing so. Now, he’s thoroughly overhauled Code Complete to reflect all that’s happened since 1994. Web programming. Agile and collaborative methods. Patterns. Refactoring.
There are some code examples here -- now in C#, VB.NET, and Java. (And object-oriented techniques are now woven throughout.) But the heart of the book is still how to think more clearly at every level.

How much planning is enough for your project? How do you manage complexity? Choose the right language for the task? Write higher-quality code? Organize it effectively? Cope with the realities of integration? Few books deal well with questions like these. Code Complete, Second Edition does, and it’s indispensable."

does that answer the question of whether it would be worth a few extra quid?

AW

0
 
LVL 7

Assisted Solution

by:Jenn3
Jenn3 earned 100 total points
ID: 13758038
There are many good ideas put forth right here in EE and above. It's easy for me to tell you which book to buy, but that doesn't really help.

My view is to use - Logic and Software Engineering techniques.

Languages and Engineering
-------------------------------
I have been playing with codes for a while from C, C++, Java and VB, and software engineering techniques is much more important than those actual languages... i must confess.

Languages deals with Syntax more than Processes. Processes are constructed from basic algorithm steps. Software Engineering is about building efficient and good Processes by using various programming methodologies.

For example: An architect/engineer might not know the best way to hammer a piece of wood to the ceiling, but (s)he will know how to design a big building withstanding 200miles wind while costing as little as possible. A brick layer or carpenter won't know how to design a big building, but (s)he sure knows how to build a small one.

Learn About Engineering Techniques
------------------------------------------
Programming is so similar to building construction. Not knowing engineering methods will allow you to create a program to some extent in size. When things gets bigger, there'll be plenty of code repeats and unorganized process loops.

[1] Research Requirements then Plan and Plan and Plan. Spaghetti codes comes from bad planning with plenty ad-hoc codes. This introduces bad logics which cause unexpected bugs and difficulty in maintenance after 6 -12 months.

How well does ad-hoc codes work with previously coded procedures and routines? It's a real danger when dealing with an evolving project that spans 3-5 or more years because.. people tend to forget why they write something.

I spend 60% of my time in Research-Plan-Design phase. Actual coding time takes up 25-30%. Rest is client visitations, debuging, testing and profiling the beta versions.

[2] OO - Object Oriented (Software Engineering/Programming/Design). Shouldn't leave home without it. Create your own Toolbox (of codes) with classes, modules & etc.

[3] Code Reviews (everyday) - Read codes and review them for flaws without adding anything new. There are some 3rd party tools that can help such as DevPartner.

[4] Process Analysis & Logic Modelling - Just about using logic and common sense in finding the best way to do something with plenty of options for flexibility.Before adding new codes, read existing codes and see it like a map. Once you know how everything is linked and tied together, then add the new lines.

[5] UI (User Interface) Engineering - This is important!!!! >"< 
There are generally two approach in dealing with design. Design from Core and then move outward to what the final user will see. The second approach is to first design what we know each users wish to see and do, lay it out in forms then gradually move the design deeper into the core logic engine (processes), data structures or schema, system redundancies and finally error handling.

[6] PLAY GAMES!!! As a programmer, it pays to see what good software looks like and how efficient they work (i.e. HalfLife 2). Also a good reason to avoid seeing more codes in the sleep.

Don't learn everything without trying things first and asking people about it... because we as programmers just don't have a lot of time for learning useless tools (besides getting drunk and sky diving from our window - my personal view)

GO Play GAMES!!!
0
 
LVL 3

Assisted Solution

by:mathbiol
mathbiol earned 80 total points
ID: 13758195
Paul,

The term "spaghetti code" originated as a criticism of badly written Fortran code that had GOTOs all over the place.  If you drew on your print-out to show where control went next, you ended up with curvy connections going here, there and yon, with lots of crossing of the curvy lines.  The resulting mess of curvy criss-crossing lines looked something like spaghetti.  Or Medusa's snakes.

Then structured languages were invented that didn't allow this (Cobol, Pascal, etc.).  And Fortran underwent a reform.

Along came C, which permitted the development of bad habits.

Subsequently object-oriented programming was developed.  From reading the discussion, I think the term "spaghetti code" has come to be synonymous with "lousy code" for many people.  But for me, it still has the original meaning, which was hard-to-read code.  Good luck to you if you had the job of modifying some spaghetti code written by someone else (with, naturally, no documentation)!

If you developed some bad habits as an unstructured, self-taught C programmer, you could straighten yourself out with any structured programming book from the eighties that appeals to you from the library or second-hand shop.  Pascal would be an eminently safe choice.  Books from that period were quite focussed on curing people of spaghettitus.

mathbiol
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13760312
mathbiol,

Thanks for the history.

There is another factor tha causes spaghetti and thats lots of coders and no programmers but we'll get to that.

I've always felt that the best cure was to be forced to support your own code for a few years. You quickly learn how to write kind software.

I will review and summarise all you points soon. Right now I got some spaghetti to work on. ;)

Paul
0
 
LVL 10

Expert Comment

by:fds_fatboy
ID: 13760468
In answer to PaulCaswell:

A definition of clever code is ingenious code which is difficult to follow. About 15 years ago, I ended up looking after code which was about 12 years old at the time. The previous owner of it had recently left the company. He was a very clever man and my boss at the time said (with a sense of irony) that the code was a lasting monument to his intellect. It was unmaintainable.

Later I spent over five years working in a bespoke software house (mainly on fixed-price projects) and another five working as an independent contractor (I am now gainfully employed again by my last customer). In that time, I would be picking code up off other people, dropping it, moving between projects every couple of months. Spaghetti code would not work in that environment.

I now believe that good design documentation and coding standards are the most important part of an ifrastructure. A good code/object library and peer review. If your code is not instantly understandable in a peer review - it is not easily maintainable and you should attempting to break it down.

As for the cost of the project. It is far cheaper to rewrite it during development than for someone to attempt to maintain it. Of course if you have a decent specification/design documentation, the maintainer can always throw away and rewrite the offending code from the spec.

To recap. Simple code is easily understandable code (that another coder can understand without having to talk to the coder and without needing specialised business/mathematical etc knowledge). At times there is little or no choice but to write something complicated. This is what comments and documentation are for.

There is one other point I would like to make. Self documenting code is a myth (IMHO).

I don't necessarilly agree about not leaving functions early. Sometimes, it avoids "Chevrons" and code disappearing off the right-hand side of the screen.

As for the avoiding gotos. I'll stand by that - mean jumps with no structure. There are times when jumps are allowed - but only in rare exception to the general rule (e.g. in VB error handling).
0
 
LVL 10

Expert Comment

by:fds_fatboy
ID: 13760489
I almost forgot. Don't code your way out of trouble. I've seen lots of times a coder attempts something and it doesn't quite work, so he/she starts adding code to attempt to fix it. And carries on adding until it works, when it would have been better to stop, reassess why the original code didn't work and if necessary, start again.
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 13761029
I feel that goto and  returning early do not lead to sphagetti code ... these are tools (and very useful ones) which need to be used *responsibly* in order to get maximum advantage ... An as example, check some files in Linux kernel source code ... You will find early returns and some gotos but they would all be easy to follow and sort of blend into the flow rather than disrupt it.

It is easy to create a complicated if condition or nest complex function calls and render the code unreadable.

In short, it is not the tool, but how you use the tool that matters.

From what I have learnt, best way to avoid sphagetti code is
- Have a well defined framework for common functionality, e.g. logging, debugging, profiling etc. When each programmer adds his own customized code (with personal touches ofcourse) for such functionality that code starts looking irritating ...

- I do like the idea of peer review as mentioned by fds_fatboy

- Clean interfaces

- Proper planning with fore-thought to future

- No stuffing of multiple calls in a single line

- Minimum possible dependence on variable sizes, endianess etc.

- All bug fixes documented in the code and revision history... It is fixes which normally add exceptions to rules

- Have coding standards and naming conventions

- Experience counts ... after a while you develop a knack of whats readable and whats not ... sometimes hacks and clever code are required ... trick is to identify when they can be done away with

Cheers!
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13761249
Thanks all. Keep em coming. I'll try to distill out a list of do's soon and represent for your discussion.

I'd rather steer clear of donts if I can so, for example, the discussion about gotos and mid-function returns might be distilled into 'make sure the code is obviously predictable'. How does that sound?

Paul
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 13762699
Aurthur, that answers it for me :)  hehe, I didn't realise how many years were between the two releases. ;) Cheers!

Back to the discussion..

I suppose that another tip would be to use indents (obviously), but make sure that they're the correct size; some people use extremely large indents, and they just make the code more difficult to understand.. Likewise, some people use very small indents (if any), obviously, this makes understanding of the codes' structure extremely difficult and tedious.

Also, I find that when programming something very large, it helps to space out any functions by an obvious amount, whereas most programmers (well, most that I recall seeing) only use a single line between each function. At least subconciously, you will be able to interpret the code better, and find certain functions, etc, quicker and easier, when it's all nicely spaced :)

Then there's the names of variables; I am still trying to break the habbit of just calling variables "flag1", "flag2", etc. lol. Give them appropriate names! And also, the way that variables a presented (especially class variables).
When there's a lot of variables, it's very unclear when they are presented like this:

private int variabl1 = 1;
private String someString = "hello";
public long someNumber = 10009;
...

Instead, I at least aim to lay them out like so (in columns):

private    int           variable1           = 1;
private    String      someString        = "hello";
private    long         someNumber     = 10009;
...

(although it looks even nicer when presented in a syntax-highlighting editor).


If you're working working with someone elses spaghetti code, then sometimes, it looks a bit obfuscated :) , so, what you could do, is get an existing program (if you can't be bothered to re-invent the wheek), which will turn any obfuscated code into neater, nicely indented, nicely presented, code  ^_^

Once again; I'll see if I can think up much more :)
0
 
LVL 25

Expert Comment

by:InteractiveMind
ID: 13762740
lol - please excuse the odd+ typo; I am aware of my terrible typing :)
0
 
LVL 5

Expert Comment

by:beryl666
ID: 13766307
wad4ever:
>>More recently, we have pattern-oriented design.
may i know what is pattern-oriented design and how it is different with object oriented?

Jenn3:
may i know what is ad-hoc codes?

PaulCaswell:
may i know what is  mid-function returns?

anyone knows also can answerme .

Thanks to all, i learn a lot from here.
0
 
LVL 10

Expert Comment

by:fds_fatboy
ID: 13767866
I believe that "ad-hoc codes" means coding on the fly - or coding without due thought and design.

Mid-function returns are just that - return statements in the middle of your functions. The functions with mid-function returns can also be described as functions with more than one exit point.
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13770264
Beryl,

Here's some code:

void Function ( void )
{
 FILE * f;
 ...
 f = fopen ("FileName", "rb");
 if ( !f ) return; // Mid-function return.
 ...
 fclose (f);
}

Some months later someone else comes along and changes it to:

void Function ( void )
{
 FILE * f;
 char * mem;
 ...
 mem = malloc (10);
 if ( !mem ) return;
...
 f = fopen ("FileName", "rb");
 if ( !f ) return; // Mid-function return.
 ...
 free ( mem );
 fclose (f);
}

Then later, a different programmer changes it to:

void Function ( void )
{
 FILE * f;
 char * mem;
 FILE * g;
 ...
 mem = malloc (10);
 if ( !mem ) return;
...
 g = fopen ("NewFile", "wb");
 if ( !g ) return;
...
 f = fopen ("FileName", "rb");
 if ( !f ) return; // Mid-function return.
 ...
 free ( mem );
 fclose (f);
 fclose (g);
}

Then, years later, someone deletes the file "FileName" and the whole program crashes because of memory leaks and file handle leaks. Another programmer, call this programmer Beryl666, is sent in to find out what the problem was.

1. How long does it take to fix it?
2. After you've fixed it, is it going to break again?
3. If you were allowed to rewrite the whole function, how would you do it?

Now go through the same exercise but disallow mid-function returns. The final result is probably something like:

void Function ( void )
{
 char * mem;
 ...
 mem = malloc (10);
 if ( mem )
 {
 FILE * g;
 ...
 g = fopen ("NewFile", "wb");
 if ( g )
 {
   FILE * f;
   ...
   f = fopen ("FileName", "rb");
   if ( f )
   {
     ...
     fclose ( f );
   }
   ...
   fclose(g);
 }
  ...
  free (mem);
 }
}

Do you see now how banning mid-function returns leaves the code in a malleable form whereas allowing them makes for something exceptionally difficult to change or even guarantee. Similar arguments apply to gotos.

Paul
0
 
LVL 10

Expert Comment

by:fds_fatboy
ID: 13770491
Paul, I understand your point, but I still would not ban them. The rules of programming are that you clear up after yourself. If you clear up after before a return statement all is well and good

I can see nothing wrong with this:

    int doSomething()
    {
        // early exit condition
        if(loading)
            return 1;
        ...
        ...
        ...
       return 1;
    }



 and anything that stops this kind of thing can't be bad:

       ...
       ...
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return 1;
    }
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13770698
fds_fatboy,

I have no intention of asserting my preferences on others. The way I avoid chevrons is to refactor. Generally, if you minimise scope variables it is simple to trivial to pull out isolatable sections of code into separate functions.

void Function ( void )
{
 char * mem;
 ...
 mem = malloc (10);
 if ( mem )
 {
 FILE * g;
 ...
 g = fopen ("NewFile", "wb");
 if ( g )
 {
   FILE * f;
   ...
   f = fopen ("FileName", "rb");
   if ( f )
   {
     ...
     fclose ( f );
   }
   ...
   fclose(g);
 }
  ...
  free (mem);
 }
}

Could easily become:

void Function ( void )
{
 char * mem;
 ...
 mem = malloc (10);
 if ( mem )
 {
  WorkWithFiles (mem);
  free (mem);
 }
}

void WorkWithFiles ( char * mem )
{
 FILE * g;
 ...
 g = fopen ("NewFile", "wb");
 if ( g )
 {
   FILE * f;
   ...
   f = fopen ("FileName", "rb");
   if ( f )
   {
     ...
     fclose ( f );
   }
   ...
   fclose(g);
 }
  ...
}

This process would be as complex as a rewrite with the spaghetti version.

Paul
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 13770909
I had always been taught to avoid gotos and I never actually used it. I had developed a mental barrier to using gotos until I saw them being used in Linux kernel ... They used it beautifully for exits from functions ... Gotos sometimes do come handy in these kind of situations

mem= malloc(10);
if ( NULL == mem )
       goto NOMEM;
...
f = fopen ("myfile", "w")
if ( NULL == f )
       goto NOFILE;
...
...
return ALL_OK;

NOMEM:
return NO_MEM_ERR;

NOFILE:
free (mem);
return NO_FILE_ERR;

Ofcourse with multiple mallocs and more processing the code needs better restructuring, but gotos sometimes do provide a neat way of getting out of the function. Once again, they should not be used in every function ... Just when you need them.
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13770973
>>Ofcourse with multiple mallocs and more processing the code needs better restructuring
My point exactly! Coding for the future DEMANDS that you do not use goto because all you are doing is either making someone else structure it correctly later, when the design has been forgotten, or encouraging them not to use it because it is difficult to enhance. Neither route is of benefit to anyone and the only saving is a few seconds of coding it correctly.

Essentially, brevity *can* imply correctness but can also imply the opposite.

We are talking here about avoiding spaghetti code in the future as well as now. This may not seem to be spaghetti now but, as it eveolves, and all software does, it will become more and more difficult to enhance. I hope this is not a prediction of the future of linux because that would be a shame.

My question was phrased carefully. I want to avoid ALL spaghetti, now AND in the future.

Paul
0
 
LVL 7

Expert Comment

by:Jenn3
ID: 13771056
I agreed with you on not ruling out Goto.

Badly structured processes involving multiple nested modules, functions and subroutines on a large project with i.e. over a 1/2 million SLOC or more (an arbitrary figure), can have a similar feel of indiscriminate usage of Gotos.

In Reality, spaghetti codes do occur in majority of projects that i have encountered except in some well planned and documented projects. To finish a project within budget and schedule coupled with last minute changes in client's requirements and limited staff is one of the more common inducing factor.

It is extremely easy to have plates of spaghetti served in a project when you're the only programmer because single developer has little time to review processes and codes... unless you're coding maverick :)
0
 
LVL 45

Expert Comment

by:sunnycoder
ID: 13771068
Paul, I do not have the source code at hand ... its been a few months since I looked at it ... It had evolved very well and was very readable ... It has been worked upon by thousands of developers all around the globe for several years now and has personal touches from all of them. It still uses goto and is readable ... I believe Linux kernel source code structuring has some important lessons to impart in this direction ... I remember seeing a FAQ kind of thing for linux kernel developers which addressed the specific issue of how to write code for the kernel. Let me see if I can find it now.
0
 
LVL 10

Expert Comment

by:fds_fatboy
ID: 13771184
If the ground rules are set out and abided by, the use of goto can be fine (contrary to what I wrote right up at the top there). A very long time ago I learnt Cobol using Jackson Structured Programming using Inline Gotos in a very structured manner (it was still horrible).

And when you get to machine level where would we be without the jmp statement?

I think where the discussion is going is like this:
Avoiding unstructured jumps around code and making sure any toys you get out are put back in the box are the main rules to implement.
Good design, documentation and proper forethought are the best tools to avoid spaghetti.

Forgive me if I have over simplified or just plain got it wrong.
0
 
LVL 7

Expert Comment

by:Jenn3
ID: 13772898
beryl666, this is for you ;)

Ad Hoc Codes are improvised and often impromptu lines added to fix or add a feature or two without looking at the larger design framework. It's a quick but dirty approach. The advantage is simply SPEED of delivery but comes with problems spanning from EFFICIENCY to LOGICAL BUGS.

It is common thing among developers of customized projects. Frequently, after a project has been completed and case closed (payment collected), there's little resources a company/department has to assign a thorough code review for an optimized solution. It's very easy to say "we'll come back with a more efficient solution...", but never.

DESIGN FOR NOW? or
DESIGN FOR THE FUTURE?

This is one of the biggest conceptualization idea and broadest issue we ask when dealing with new project. This is important because it deals with:

HIGH SPEED DEVELOPMENT? or
HIGH CHANGE DEVELOPMENT?

There is an ocean worth of difference between coding by yourself and coding with a huge professional team. For working by yourself, one could throw many rules out the window and code the way you want. In a large firm that conforms to CMM (Capability Maturity Model), things do become a bit more structured. Coding spaghetti can see one's bonus disappear.

For small project with limited functionalities, it's more profitable to CODE FAST. Almost always, these clients don't really know what they want. If the client wants something bigger, we'll start with a new Code Base. It's faster that way.
0
 
LVL 7

Expert Comment

by:Jenn3
ID: 13772970
How well do you rate yourself on CMM/CMMI, see this link:

http://en.wikipedia.org/wiki/Capability_Maturity_Model
0
 
LVL 16

Author Comment

by:PaulCaswell
ID: 13955207
All,

Thanks for your valuable input. I was intending to summarise with a list but I realised that that would lower the value of all the discussion.

Essentially, there isnt a single method of spaghetti avoidance, nor are there hard-and-fast rules. Each rule must be flexible but valuable.

Thanks again for all the suggestions.

Paul
0
 
LVL 46

Expert Comment

by:Kent Olsen
ID: 13995874

Wish that I'd have been following this thread.  :)

Hi Sunny.  Your sample kernel code is below.   Note that when the function is several hundred lines long, as this one could be, your attention is diverted off the page simply to find the funciton exit.

mem= malloc(10);
if ( NULL == mem )
       goto NOMEM;
...
f = fopen ("myfile", "w")
if ( NULL == f )
       goto NOFILE;
...
...
return ALL_OK;

NOMEM:
return NO_MEM_ERR;

NOFILE:
free (mem);
return NO_FILE_ERR;


This can be done just as effectively without GOTO.

#define RETURN(x) {if(mem)free(mem);return(x);}
mem= malloc(10);
if ( NULL == mem )
  RETURN (NO_MEM_ERR);
...
f = fopen ("myfile", "w")
if ( NULL == f )
  RETURN (NO_FILE_ERR);
...
...
  RETURN (ALL_OK);

And, of course, if one is concerned about the couple of machines instructions wasted checking mem before the return, you simply define two macros, one simply returns, the other frees and returns.

I'm still opposed to GOTO.  Except when it's used to suggest a destination to certain people.  ;)
Kent
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

What do responsible coders do? They don't take detrimental shortcuts. They do take reasonable security precautions, create important automation, implement sufficient logging, fix things they break, and care about users.
When you discover the power of the R programming language, you are going to wonder how you ever lived without it! Learn why the language merits a place in your programming arsenal.
With the power of JIRA, there's an unlimited number of ways you can customize it, use it and benefit from it. With that in mind, there's bound to be things that I wasn't able to cover in this course. With this summary we'll look at some places to go…
Starting up a Project

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question