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.
“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
returnstatements 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
whilestatements 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.