Is goto ok for breaking out of nested loops? - c#

JavaScript supports a goto like syntax for breaking out of nested loops. It's not a great idea in general, but it's considered acceptable practice. C# does not directly support the break labelName syntax...but it does support the infamous goto.
I believe the equivalent can be achieved in C#:
int i = 0;
while(i <= 10)
{
Debug.WriteLine(i);
i++;
for(int j = 0; j < 3; j++)
if (i > 5)
{
goto Break;//break out of all loops
}
}
Break:
By the same logic of JavaScript, is nested loop scenario an acceptable usage of goto? Otherwise, the only way I am aware to achieve this functionality is by setting a bool with appropriate scope.

My opinion: complex code flows with nested loops are hard to reason about; branching around, whether it is with goto or break, just makes it harder. Rather than writing the goto, I would first think really hard about whether there is a way to eliminate the nested loops.
A couple of useful techniques:
First technique: Refactor the inner loop to a method. Have the method return whether or not to break out of the outer loop. So:
for(outer blah blah blah)
{
for(inner blah blah blah)
{
if (whatever)
{
goto leaveloop;
}
}
}
leaveloop:
...
becomes
for(outer blah blah blah)
{
if (Inner(blah blah blah))
break;
}
...
bool Inner(blah blah blah)
{
for(inner blah blah blah)
{
if (whatever)
{
return true;
}
}
return false;
}
Second technique: if the loops do not have side effects, use LINQ.
// fulfill the first unfulfilled order over $100
foreach(var customer in customers)
{
foreach(var order in customer.Orders)
{
if (!order.Filled && order.Total >= 100.00m)
{
Fill(order);
goto leaveloop;
}
}
}
leaveloop:
instead, write:
var orders = from customer in customers
from order in customer.Orders;
where !order.Filled
where order.Total >= 100.00m
select order;
var orderToFill = orders.FirstOrDefault();
if (orderToFill != null) Fill(orderToFill);
No loops, so no breaking out required.
Alternatively, as configurator points out in a comment, you could write the code in this form:
var orderToFill = customers
.SelectMany(customer=>customer.Orders)
.Where(order=>!order.Filled)
.Where(order=>order.Total >= 100.00m)
.FirstOrDefault();
if (orderToFill != null) Fill(orderToFill);
The moral of the story: loops emphasize control flow at the expense of business logic. Rather than trying to pile more and more complex control flow on top of each other, try refactoring the code so that the business logic is clear.

I would personally try to avoid using goto here by simply putting the loop into a different method - while you can't easily break out of a particular level of loop, you can easily return from a method at any point.
In my experience this approach has usually led to simpler and more readable code with shorter methods (doing one particular job) in general.

Let's get one thing straight: there is nothing fundamentally wrong with using the goto statement, it isn't evil - it is just one more tool in the toolbox. It is how you use it that really matters, and it is easily misused.
Breaking out of a nested loop of some description can be a valid use of the statement, although you should first look to see if it can be redesigned. Can your loop exit expressions be rewritten? Are you using the appropriate type of loop? Can you filter the list of data you may be iterating over so that you don't need to exit early? Should you refactor some loop code into a separate function?

IMO it is acceptable in languages that do not support break n; where n specifies the number of loops it should break out.
At least it's much more readable than setting a variable that is then checked in the outer loop.

I believe the 'goto' is acceptable in this situation. C# does not support any nifty ways to break out of nested loops unfortunately.

It's a bit of a unacceptable practice in C#. If there's no way your design can avoid it, well, gotta use it. But do exhaust all other alternatives first. It will make for better readability and maintainability. For your example, I've crafted one such potential refactoring:
void Original()
{
int i = 0;
while(i <= 10)
{
Debug.WriteLine(i);
i++;
if (Process(i))
{
break;
}
}
}
bool Process(int i)
{
for(int j = 0; j < 3; j++)
if (i > 5)
{
return true;
}
return false;
}

I recommend using continue if you want to skip that one item, and break if you want to exit the loop. For deeper nested put it in a method and use return. I personally would rather use a status bool than a goto. Rather use goto as a last resort.

anonymous functions
You can almost always bust out the inner loop to an anonymous function or lambda. Here you can see where the function used to be an inner loop, where I would have had to use GoTo.
private void CopyFormPropertiesAndValues()
{
MergeOperationsContext context = new MergeOperationsContext() { GroupRoot = _groupRoot, FormMerged = MergedItem };
// set up filter functions caller
var CheckFilters = (string key, string value) =>
{
foreach (var FieldFilter in MergeOperationsFieldFilters)
{
if (!FieldFilter(key, value, context))
return false;
}
return true;
};
// Copy values from form to FormMerged
foreach (var key in _form.ValueList.Keys)
{
var MyValue = _form.ValueList(key);
if (CheckFilters(key, MyValue))
MergedItem.ValueList(key) = MyValue;
}
}
This often occurs when searching for multiple items in a dataset manually, as well. Sad to say the proper use of goto is better than Booleans/flags, from a clarity standpoint, but this is more clear than either and avoids the taunts of your co-workers.
For high-performance situations, a goto would be fitting, however, but only by 1%, let's be honest here...

int i = 0;
while(i <= 10)
{
Debug.WriteLine(i);
i++;
for(int j = 0; j < 3 && i <= 5; j++)
{
//Whatever you want to do
}
}

Unacceptable in C#.
Just wrap the loop in a function and use return.
EDIT: On SO, downvoting is used to on incorrect answers, and not on answers you disagree with. As the OP explicitly asked "is it acceptable?", answering "unacceptable" is not incorrect (although you might disagree).

Related

Good pattern for multiphase algorithm?

Is there a pattern (refactoring) to improve this piece of code?
int phase = 0;
foreach (var some in arrayOfSome)
{
if (phase == 0)
{
bool result = DoSomething_0(some);
if (result) phase = 1;
}
else if (phase == 1)
{
bool result = DoSomething_1(some);
if (result) phase = 0;
result = DoSomething_1_0(some);
if (result) phase = 2;
}
else if (phase == 2)
{
bool result = DoSomething_2(some);
if (result) break;
}
}
First of all, I want to reduce the number of conditional operators and make the code more readable.
An elegant approach is to eliminate the if/then logic altogether. You can do this by creating an array of delegates indexed by state (phase). Each delegate slot in the array points at a function (or lambda) that does whatever and returns the new state (phase).
In these kinds of designs, you often end up with a loop that contains a single statement like this:
foreach (var x in data)
{
state = handler[state](x);
}
I've coded this kind of FSM many times and they are very generic when done correctly and very reliable. Bugs almost always boil down to small errors in handlers or incorrect handlers being defined for a given state/input combination.
A more general and powerful design has this pattern:
foreach (var x in data)
{
state = handler[state,x](x);
}
Where both the state and datum are used to select the handler delegate. There are huge benefits when using this pattern in that the temptation to add extra flags and conditions within the loop as the code or functionality grows over time.
The code you posted is OK but if - after time - one ends up with ten different states and umpteen conditions and many handlers then very subtle hard to fix bugs will creep in that are almost impossible sometimes to fix.
Don't see the need for refactoring here. Maybe you could reduce some lines and write it like this:
int phase = 0;
foreach (var some in arrayOfSome)
{
if (phase == 0)
{
if (DoSomething_0(some)) phase = 1;
}
if (phase == 1)
{
if (DoSomething_1(some)) phase = 0;
if (DoSomething_1_0(some)) phase = 2;
}
if (phase == 2)
{
if (DoSomething_2(some)) break;
}
}
If you are concerned with too many if's within a for (again it is readable in your case) you can have a look at Flattening Arrow Code

Foreach item i in collection of lists

Is there a classy way to do:
foreach(item i in ListItems1)
do ...
foreach(item i in ListItems2)
do ...
foreach(item i in ListItems2)
do ...
...
In a single foreach (using Linq I suppose ?) in C#, that does not hurt performance (especially the memory side) ?
The best way to manage this is to factor it into a function that you call 3 times:
public void ProcessList(List<myListType> theList)
{
//Do some cool stuff here...
}
But it's borderline whether you get much maintainability benefit with this. If you don't want to increase memory usage then this is probably the best refactor to make your code better. Unless your lists are huge the memory differences are likely to be negligible anyway.
You can always do
foreach (item i in ListItems1.Concat(ListItems2).Concat(ListItems3))
{
// do things
}
There's also the similar .Union() that removes duplicate items. However, since it is removing duplicates, it's less performant.
For the sake of answering your question and being a little creative, this here "technically" would work but I wouldn't advice using it.
int listItemTotalItemCount = ListItems1.Count() + ListItems2.Count() + ListItems3.Count();
for(int i = 0; i < listItemTotalItemCount; i++)
{
int listIndex = i;
object retrievedItem;
if(listIndex >= ListItems1.Count())
{
if (i - ListItems1.Count() >= ListItems2.Count())
{
retrievedItem = ListItems3[i - ListItems1.Count()- ListItems2.Count() ];
}
else
{
retrievedItem = ListItems2[i - ListItems1.Count()];
}
}
else
{
retrievedItem = ListItems1[listIndex];
}
retrievedItem.DoSomethingSpecial();
}
This can probably be improved as well with an array of the lists you want to iterate over, but as I said before I would not recommend this method as it is I'm guessing significantly worse than your original method.

Equivalent of Ruby "redo" in C#

Is there an equivalent method of performing the job of redo in C#? i.e. going back to the top of the loop and re-execute without checking conditions or increasing the loop counter. Thanks.
for (int i = 0; i < 100; i++)
{
do
{
DoYourStuff();
} while (ShouldWeDoThatAgain());
}
Do...while is like a standard while loop, except instead of checking its conditional before each iteration, it checks after. That way, the code inside the loop will always execute at least once. Stick that inside a for or foreach loop, and that should get you the behavior your want. This is a bit simpler than Simon's answer, as it doesn't require an extra variable, doesn't use continue, and doesn't mess with the loop counter at all.
Why not simply:
Although goto is not really everyone's favourite, it's quite readable in this case...
for(...)
{
redo:
//...
if (...)
goto redo;
}
No. The closest you'll get is something like this:
bool redoCalled = false:
for (int i = 0; i < 10; i++) {
if (redoCalled) {
i--;
redoCalled = false;
}
// other stuff here
if (redoWanted) {
redoCalled = true;
continue;
}
}

How to break out of nested for loops [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Breaking out of a nested loop
How to break out of 2 loops without a flag variable in C#?
Hello I have a function that has nested loops. Once the condition has been met, I want to break out of nested loops. The code is something like this below:
foreach (EmpowerTaxView taxView in taxViews)
{
foreach (PayrollEmployee payrollEmployee in payrollEmployees)
{
//PayStub payStub = payrollEmployee.InternalPayStub;
IReadOnlyList<PayrollWorkLocation> payrollWorkLocations = payrollEmployee.PayrollWorkLocations;
foreach (PayrollWorkLocation payrollWorkLocation in payrollWorkLocations)
{
Tax tax = GetTaxEntity(payrollWorkLocation, taxView.BSITypeCode, taxView.BSIAuthorityCode,
paidbyEr, resCode);
if (tax != null && tax.Rate.HasValue)
{
taxRate = tax.Rate.Value;
break;
}
}
}
}
Unfortunately, break comes out of only one loop. I want to break out of the whole thing. Please, I know some people have suggested goto: statement. I am wondering is there any other way around, such writing some LINQ queries to the same effect.
Any ideas and suggestions are greatly appreciated !
Two options suggest themselves as ways of getting out without having an extra flag variable to indicate "you should break out of the inner loop too". (I really dislike having such variables, personally.
One option is to pull all of this code into a separate method - then you can just return from the method. This would probably improve your code readability anyway - this really feels like it's doing enough to warrant extracting into a separate method.
The other obvious option is to use LINQ. Here's an example which I think would work:
var taxRate = (from taxView in taxViews
from employee in payrollEmployees
from location in employee.PayrollWorkLocations
let tax = GetTaxEntity(location, taxView.BSITypeCode,
taxView.BSIAuthorityCode,
paidbyEr, resCode)
where tax != null && tax.Rate.HasValue
select tax.Rate).FirstOrDefault();
That looks considerably cleaner than lots of foreach loops to me.
Note that I haven't selected tax.Rate.Value - just tax.Rate. That means the result will be a "null" decimal? (or whatever type tax.Rate is) if no matching rates are found, or the rate otherwise. So you'd then have:
if (taxRate != null)
{
// Use taxRate.Value here
}
Well, you could use the dreaded goto, refactor your code, or this:
// anon-method
Action work = delegate
{
for (int x = 0; x < 100; x++)
{
for (int y = 0; y < 100; y++)
{
return; // exits anon-method
}
}
};
work(); // execute anon-method
You could use a flag variable.
bool doMainBreak = false;
foreach (EmpowerTaxView taxView in taxViews)
{
if (doMainBreak) break;
foreach (PayrollEmployee payrollEmployee in payrollEmployees)
{
if (doMainBreak) break;
//PayStub payStub = payrollEmployee.InternalPayStub;
IReadOnlyList<PayrollWorkLocation> payrollWorkLocations = payrollEmployee.PayrollWorkLocations;
foreach (PayrollWorkLocation payrollWorkLocation in payrollWorkLocations)
{
Tax tax = GetTaxEntity(payrollWorkLocation, taxView.BSITypeCode, taxView.BSIAuthorityCode,
paidbyEr, resCode);
if (tax != null && tax.Rate.HasValue)
{
taxRate = tax.Rate.Value;
doMainBreak = true;
break;
}
}
}
}

How Bad is this Code?

Ok, I am an amateur programmer and just wrote this. It gets the job done, but I am wondering how bad it is and what kind of improvements could be made.
[Please note that this is a Chalk extension for Graffiti CMS.]
public string PostsAsSlides(PostCollection posts, int PostsPerSlide)
{
StringBuilder sb = new StringBuilder();
decimal slides = Math.Round((decimal)posts.Count / (decimal)PostsPerSlide, 3);
int NumberOfSlides = Convert.ToInt32(Math.Ceiling(slides));
for (int i = 0; i < NumberOfSlides; i++ )
{
int PostCount = 0;
sb.Append("<div class=\"slide\">\n");
foreach (Post post in posts.Skip<Post>(i * PostsPerSlide))
{
PostCount += 1;
string CssClass = "slide-block";
if (PostCount == 1)
CssClass += " first";
else if (PostCount == PostsPerSlide)
CssClass += " last";
sb.Append(string.Format("<div class=\"{0}\">\n", CssClass));
sb.Append(string.Format("<img src=\"{2}\" alt=\"{3}\" />\n", post.Custom("Large Image"), post.MetaDescription, post.ImageUrl, post.Title));
sb.Append(string.Format("<a class=\"button-launch-website\" href=\"{0}\" target=\"_blank\">Launch Website</a>\n", post.Custom("Website Url")));
sb.Append("</div><!--.slide-block-->\n");
if (PostCount == PostsPerSlide)
break;
}
sb.Append("</div><!--.slide-->\n");
}
return sb.ToString();
}
Use an HtmlTextWriter instead of a StringBuilder to write HTML:
StringBuilder sb = new StringBuilder();
using(HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(sb)))
{
writer.WriteBeginTag("div");
writer.WriteAttribute("class", "slide");
//...
}
return sb.ToString();
We don't want to use an unstructured writer to write structured data.
Break the body of your inner loop into a separate routine:
foreach(...)
{
WritePost(post, writer);
}
//snip
private void WritePost(Post post, HtmlTextWriter writer)
{
//write single post
}
This makes it testable and more easily modifiable.
Use a data structure for managing things like CSS classes.
Instead of appending extra class names with a space and hoping everything lines up right at the end, keep a List<string> of class names to add and remove as necessary, and then call:
List<string> cssClasses = new List<string>();
//snip
string.Join(" ", cssClasses.ToArray());
Instead of this,
foreach (Post post in posts.Skip<Post>(i * PostsPerSlide))
{
// ...
if (PostCount == PostsPerSlide)
break;
}
I'd move the exit condition into the loop like so: (and eliminate unnecessary generic parameter while you're at it)
foreach (Post post in posts.Skip(i * PostsPerSlide).Take(PostsPerSlide))
{
// ...
}
As a matter of fact, your two nested loops can probably be handled in one single loop.
Also, I'd prefer to use single quotes for the html attributes, since those are legal and don't require escaping.
It's not great but I've seen much much worse.
Assuming this is ASP.Net, is there a reason you're using this approach instead of a repeater?
EDIT:
If a repeater isn't possible in this instance I would recommend using the .Net HTML classes to generate the HTML instead of using text. It's a little easier to read/adjust later on.
I've seen much worse, but you could improve it quite a bit.
Instead of StringBuilder.Append() with a string.Format() inside, use StringBuilder.AppendFormat()
Add some unit tests around it to ensure that it's producing the output you want, then refactor the code inside to be better. The tests will ensure that you haven't broken anything.
My first thought is that this would be very difficult to unit test.
I would suggest having the second for loop be a separate function, so you would have something like:
for (int i = 0; i < NumberOfSlides; i++ )
{
int PostCount = 0;
sb.Append("<div class=\"slide\">\n");
LoopPosts(posts, i);
...
and LoopPosts:
private void LoopPosts(PostCollection posts, int i) {
...
}
If you get into a habit of doing loops like this then when you need to do a unit test it will be easier to test the inner loop separate from the outer loop.
I'd say that it looks good enough, there is no serious problems with the code, and it would work well. It doesn't mean that it can't be improved, though. :)
Here are a few tips:
For general floating point operations you should use double rather than Decimal. However, in this case you don't need any floating point arithmetic at all, you can do this with just integers:
int numberOfSlides = (posts.Count + PostsPerSlide - 1) / PostsPerSlide;
But, if you just use a single loop over all items instead of a loop in a loop, you don't need the slide count at all.
The convention for local variables is camel case (postCoint) rather than pascal case (PostCount). Try to make variable names meaningdful rather than obscure abbreviations like "sb". If the scope of a variable is so small that you don't really need a meaningful name for it, just go for the simplest possible and just a single letter instead of an abbreviation.
Instead of concatenating the strings "slide block" and " first" you can assign literal strings directly. That way you replace a call to String.Concat with a simple assignment. (This borders on premature optimisation, but on the other hand the string concatenation takes about 50 times longer.)
You can use .AppendFormat(...) instead of .Append(String.Format(...)) on a StringBuilder. I would just stick to Append in this case, as there isn't really anything that needs formatting, you are just concatenating strings.
So, I would write the method like this:
public string PostsAsSlides(PostCollection posts, int postsPerSlide) {
StringBuilder builder = new StringBuilder();
int postCount = 0;
foreach (Post post in posts) {
postCount++;
string cssClass;
if (postCount == 1) {
builder.Append("<div class=\"slide\">\n");
cssClass = "slide-block first";
} else if (postCount == postsPerSlide) {
cssClass = "slide-block last";
postCount = 0;
} else {
cssClass = "slide-block";
}
builder.Append("<div class=\"").Append(cssClass).Append("\">\n")
.Append("<a href=\"").Append(post.Custom("Large Image"))
.Append("\" rel=\"prettyPhoto[gallery]\" title=\"")
.Append(post.MetaDescription).Append("\"><img src=\"")
.Append(post.ImageUrl).Append("\" alt=\"").Append(post.Title)
.Append("\" /></a>\n")
.Append("<a class=\"button-launch-website\" href=\"")
.Append(post.Custom("Website Url"))
.Append("\" target=\"_blank\">Launch Website</a>\n")
.Append("</div><!--.slide-block-->\n");
if (postCount == 0) {
builder.Append("</div><!--.slide-->\n");
}
}
return builder.ToString();
}
It would help if the definition for posts existed, but in general, I would say that generating HTML in code behind is not the way to go in Asp.Net.
Since this is tagged as .Net specifically...
For displaying a list of items in a collection, you'd be better off looking at one of the data controls (Repeater, Data List, etc) and learning how to use those properly.
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/default.aspx
Another piece of tightening you could do: replace the sb.Append(string.Format(...)) calls with sb.AppendFormat(...).

Categories

Resources