Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exit for = spaghetti code?

I have always been taught to have one exit from functions and write code that doesn't jump all over the place, is the following bad code or is there a better way to write the for loop without needing an "exit for"?

dim dt as datatable = FillDataTableFunction()
dim bWrite as boolean = false
for each row as datarow in dt.rows
  if row.item("somecolumn") <> string.empty then 
    bWrite = true
    exit for
  end if 
next

if bWrite then 
  'do stuff
end if

I guess I am just thinking that this will reduce unneeded iterations through the for loop but for some reason it seems like a bad coding practice.

like image 572
Jim Avatar asked Dec 10 '10 22:12

Jim


People also ask

How do you stop spaghetti code?

To avoid losing track of where each pasta ends (or what it does), there is only one solution; avoid cluttering your plate. In fact, you should probably have only one spaghetti per plate, as they can quite easily be intricated together, and they should probably be of limited size.

What is spaghetti code word for?

Spaghetti code is a pejorative phrase for unstructured and difficult-to-maintain source code. Spaghetti code can be caused by several factors, such as volatile project requirements, lack of programming style rules, and software engineers with insufficient ability or experience.

Is League of Legends a spaghetti code?

For a long time, League of Legends had so many bugs that you could sort them into species and pick favorites. LoL had a serious spaghetti code problem, but it wasn't just spaghetti code. It was Mama's Family Recipe Spaghetti Code. LoL's code was flawed in a way that had character and humor.


1 Answers

"I have always been taught" - at some point in life, people start learning rather than being taught :-)

Don't take anything as gospel (even from me - if you disagree, make your own mind up). Look behind the guidelines to see why they exist.

The reason why you were taught that multiple exit points is bad is because they often lead to code that is hard to follow. In other words, a 400-line function peppered with return statements is hard to analyse in terms of its behaviour.

Your little code snippet does not suffer from this. The guideline I follow is: if you can see the control flow on a single screen in the editor, it's fine. And, since 12 lines will fit in any editor I've used in the past two decades, your code is very readable.

In fact, I've seen code from the "never use multiple exit points" people that is far less readable than that which would be produced by breaking their rules. It usually involves multi-condition while statements so convoluted that they have to break it across multiple lines, and is still a pain to analyse.

Aim for readability. If guidelines help with that, use them. If not, throw them out the window.

like image 137
paxdiablo Avatar answered Oct 07 '22 22:10

paxdiablo