Code Trivia: optimize the code for multiple nested loops
Posted
by CodeToGlory
on Stack Overflow
See other posts from Stack Overflow
or by CodeToGlory
Published on 2010-03-26T16:43:28Z
Indexed on
2010/03/26
17:03 UTC
Read the original article
Hit count: 635
I came across this code today and wondering what are some of the ways we can optimize it.
Obviously the model is hard to change as it is legacy, but interested in getting opinions.
Changed some names around and blurred out some core logic to protect.
private static Payment FindPayment(Order order, Customer customer, int paymentId)
{
Payment payment = Order.Payments.FindById(paymentId);
if (payment != null)
{
if (payment.RefundPayment == null)
{
return payment;
}
if (String.Compare(payment.RefundPayment, "refund", true) != 0 )
{
return payment;
}
}
Payment finalPayment = null;
foreach (Payment testpayment in Order.payments)
{
if (testPayment.Customer.Name != customer.Name){continue;}
if (testPayment.Cancelled)
{
continue;
}
if (testPayment.RefundPayment != null)
{
if (String.Compare(testPayment.RefundPayment, "refund", true) == 0 )
{
continue;
}
}
if (finalPayment == null)
{
finalPayment = testPayment;
}
else
{
if (testPayment.Value > finalPayment.Value)
{
finalPayment = testPayment;
}
}
}
if (finalPayment == null)
{
return payment;
}
return finalPayment;
}
Making this a wiki so code enthusiasts can answer without worrying about points.
© Stack Overflow or respective owner