I have problems breaking out off these nested loops correctly. What the code is trying to do is to indicate that a customer has rented a certain movie. Both the movie and customer are compared to properties of arraylist objects and then if all checks out the name property and ID property of a movie object are added as a string to another arraylist. All this works correctly as long as I use the first movie (from movies) and the first customer (from customers) but if I try renting other movies further down my arraylist with other customers then it adds the rented movie to the customerRentedMovies arraylist but prints out the “else message”. I figure I need to break out of the foreach(blabla) loops aswell? or could goto be used? Comments was removed (looked kinda messy, can explain further if needed)
public void RentMovie(string titel, int movieID, string name, int customerID)
{
foreach (Customer customer in customers)
{
if (name == customer.Name && customerID == customer.CustomerID)
{
foreach (MovieInfo movie in movies)
{
if (titel == movie.Titel && movieID == movie.MovieID)
{
movie.rented = true;
string rentedMovie = string.Format("{0} ID: {1}", movie.Titel, movie.MovieID);
customer.customerRentedMovies.Add(rentedMovie);
break;
}
else { Console.WriteLine("No movie with that titel and ID!"); }
}
break;
}
else { Console.WriteLine("No customer with that ID and name"); }
}
}
Your method is violating the Single Responsibility rule — each class or method should have one and only one responsibility and reason for change. You have a single method that is responsible for doing 3 different things:
This makes it
This is a Code Smell.
You should refactor your method something like this, delegating the responsibility for finding a customer and finding a movie to their own methods:
If you aren’t using Linq, the
FindCustomer()andFindMoviemethods might look like this:If you’re using Ling, the same methods might be:
The code is now much simpler, easier to understand and self-describing. When it’s time to make changes, the changes will be easier to make as well.